我有一个产生id的查询,后跟一个计数。我想只得到那些计数为N的行。我尝试了下面的代码,但我得到了错误:列" cert_count"不存在'。我想我使用的标签错了吗?
cust_cert_counts = db.session.query(
CustomerCertAssociation.customer_id,
func.count(CustomerCertAssociation.certification_id).label('cert_count')).filter(
CustomerCertAssociation.certification_id.in_(cert_ids)).group_by(
CustomerCertAssociation.customer_id)
cust_cert_counts.filter('cert_count=2').all()
答案 0 :(得分:4)
您无法像这样过滤别名列:
SELECT 1 AS foo WHERE foo = 1;
您必须将其嵌套在子查询中:
SELECT * FROM (SELECT 1 AS foo) bar WHERE bar.foo = 1;
对于您的特定示例,您必须执行以下操作:
subq = cust_cert_counts.subquery()
db.session.query(subq).filter(subq.c.cert_count == 2)