Python 在烧瓶SQLAlchemy中使用计数选择
我仍然对炼金术的工作原理感到困惑。到目前为止,我有一个类似这样的查询Python 在烧瓶SQLAlchemy中使用计数选择,python,sqlalchemy,flask,flask-sqlalchemy,Python,Sqlalchemy,Flask,Flask Sqlalchemy,我仍然对炼金术的工作原理感到困惑。到目前为止,我有一个类似这样的查询 SELECT cast(a.product_id as bigint) id, cast(count(a.product_id) as bigint) itemsSold, cast(b.product_name as character varying) from transaction_details a left join product b on a.product_id = b.produc
SELECT cast(a.product_id as bigint) id, cast(count(a.product_id) as bigint) itemsSold, cast(b.product_name as character varying)
from transaction_details a
left join product b
on a.product_id = b.product_id
group by a.product_id, b.product_name
order by itemsSold desc;
我不太确定这是如何在Flask tho中转换的。如果您是SQLAlchemy新手,请阅读这两本书并熟悉它的工作方式。由于您使用的是Flask SQLAlchemy扩展,请记住,在上述教程的示例中导入的许多名称都可以通过
SQLAlchemy
类的实例访问(在Flask SQLAlchemy示例中通常命名为db
)。转换为SA时,您的SQL查询将如下所示(未经测试):
# Assuming that A and B are mapped objects that point to tables a and b from
# your example.
q = db.session.query(
db.cast(A.product_id, db.BigInteger),
db.cast(db.count(A.product_id), db.BigInteger).label('itemsSold'),
db.cast(B.product_name, db.String)
# If relationship between A and B is configured properly, explicit join
# condition usually is not needed.
).outerjoin(B, A.product_id == B.product_id).\
group_by(A.product_id, B.product_name).\
order_by(db.desc('itemsSold'))