mysql - Complex 加入 Peewee

标签 mysql sql peewee

问这个问题很尴尬,因为它似乎微不足道,但我找不到有效的解决方案。

我有以下功能:

def planner(departure_id, arrival_id):
    departure = Stop.get(Stop.id == departure_id)
    arrival = Stop.get(Stop.id == arrival_id)
    buses = Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == departure)
    for bus in buses:
        print bus.line
        for stop in bus.stops:
            print stop.time, stop.stop.name

基于以下模型:

class Stop(BaseModel):
    name = CharField()
    #lat = FloatField()
    #lng = FloatField()

class Bus(BaseModel):
    line = IntegerField()
    number = IntegerField()
    direction = IntegerField()

class RideStopRelationship(BaseModel):
    bus = ForeignKeyField(Bus, related_name = "stops")
    stop = ForeignKeyField(Stop, related_name = "buses")
    time = TimeField()

关键行是 Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == department)。我正在尝试让所有将在 departurearrival 停靠的公共(public)汽车。但是,上述查询返回所有停靠在 departure 的公交车。我如何获得在“出发”和“到达”都停靠的巴士?

如果我把它弄得太复杂(要么是我的模型太复杂,要么是我的查询),请随时纠正我。

编辑: 有一种方法确实有效:

buses_departure = Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == departure)
buses_arrival = Bus.select().join(RideStopRelationship).join(Stop).where(Stop.id == arrival)
buses = Bus.select().where(Bus.id << buses_departure & Bus.id << buses_arrival)

但是对于应该是简单查询的内容来说它相当长...

最佳答案

你可以尝试这样的事情:

departure = Stop.get(...)
arrival = Stop.get(...)
query = (Bus
         .select(Bus)
         .join(RideStopRelationship)
         .where(RideStopRelationship.stop << [departure, arrival])
         .group_by(Bus)
         .having(fn.Count(Bus.id) == 2))

无关,但需要注意的一件事是,由于 python 评估运算符的方式,您需要在 in 查询中加上括号:

buses = Bus.select().where(
    (Bus.id << buses_departure) & 
    *Bus.id << buses_arrival))

关于mysql - Complex 加入 Peewee,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035009/

相关文章:

php - 选择用户喜欢的推文中的所有喜欢

php - SQL 查询在 PHPMyAdmin 中运行良好,但不适用于 mysql_query

mysql - 当 mysql 查询中缺少数据时,我想显示关系数据

c# - 使用 Expression 动态构建 Where 子句的 Entity Framework

php - Php SQLITE 中的分页

peewee - 什么可以替代 playhouse.test_utils 中的 test_database () 函数?

python - 使用 peewee 合并具有不同名称的字段

mysql - mariadb sql 默认 unix_timestamp

java - 使用 TRANSFORM 和 PIVOT 的交叉表查询重复行