我有一个查询,它产生一个id,然后是一个count。我只想得到那些有N个数的行。我尝试了下面的代码,但是我得到了“错误:列”CeltZeCalt“不存在”。我想我用错标签了?
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()
最佳答案
不能对别名列进行以下筛选:
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)