两种型号:
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 印象深刻,我相信这是可能的。
任何帮助将非常感激!