2

两种型号:

class this(DeclarativeBase):

    __tablename__ = 'this'

    'Columns'
    id = Column(Integer, primary_key=True)

    'Relations'
    that = relation('that', foreign_keys=id, backref='this')

class that(DeclarativeBase):

    __tablename__ = 'that'

    'Columns'
    id = Column(Integer, primary_key=True)
    this_id = Column(Integer, ForeignKey('this.id'))

我想运行这个简单的 SQL 查询:

SELECT id, (SELECT COUNT(*) FROM that WHERE this_id = this1.id) AS thatcount FROM this AS this1

我可以通过执行以下操作在 sqlalchemy 中获得相同的结果:

results = session.query(model.this.id, 
                        func.count(model.that.id).label('thatcount')) \
                 .join(model.that) \
                 .group_by(model.this.id)

但是,生成的 SQL 不是我想要的:

SELECT
this.id AS this_id,
count(that.id) AS thatcount 
FROM this
INNER JOIN that ON this.id = that.this_id
GROUP BY this.id

我错过了 sqlalchemy 中的一些基本思想......

1)如何在 FROM 子句中“标记”表?2) 如何创建引用父查询结果的子查询?

希望这是我不理解的简单事情,因为我对 sqlalchemy 比较陌生......当然我可以运行原始 SQL,但我对 sqlalchemy 印象深刻,我相信这是可能的。

任何帮助将非常感激!

4

1 回答 1

3
qry = select([
        this.id,
        select([func.count().label('xx')], this.id == that.this_id).as_scalar().label('thatcount'),
        ])

产生:

SELECT this.id, (SELECT count(*) AS xx
FROM that
WHERE this.id = that.this_id) AS thatcount
FROM this

直接回答您的问题:

  1. 利用label()
  2. 你不需要那个,你只需使用 的whereclauseselect指示主查询和子查询之间的连接条件。

请注意,我更喜欢func.count(that.id)这样做func.count(),因为它更明确。

于 2012-07-19T11:16:08.533 回答