2016-05-12 57 views
2

我有一個查詢產生一個id,後跟一個計數。我只想得到那些計數爲N的行。我嘗試了下面的代碼,但是我得到'錯誤:列'cert_count「不存在'。我想我使用的標籤是錯的?SQLAlchemy:使用標籤進一步過濾查詢

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

回答

3

你不能在這樣的一個別名的列過濾:

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) 
相關問題