简体   繁体   English

SQLAlchemy:使用label进一步过滤查询

[英]SQLAlchemy: Further filter query with label

I have a query that yields an id, followed by a count. 我有一个查询产生一个id,后跟一个计数。 I want to get only those rows which have a count of N. I tried the code below but I get 'error: column "cert_count" does not exist'. 我想只得到那些计数为N的行。我尝试了下面的代码,但我得到'错误:列“cert_count”不存在'。 I guess I'm using the label wrong? 我想我使用的标签错了?

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()

You can't filter on an aliased column like this: 您不能像这样过滤别名列:

SELECT 1 AS foo WHERE foo = 1;

You have to nest it in a subquery: 您必须将其嵌套在子查询中:

SELECT * FROM (SELECT 1 AS foo) bar WHERE bar.foo = 1;

For your particular example, you have to do: 对于您的特定示例,您必须:

subq = cust_cert_counts.subquery()
db.session.query(subq).filter(subq.c.cert_count == 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM