简体   繁体   English

在sqlalchemy中,如何通过使列条目相同来组合两个查询?

[英]In sqlalchemy, how can I combine two queries by having a column entry identical?

Suppose I have a mapped class User , mapped to a tables of the same name, and a column "age" for his age. 假设我有一个映射类User ,映射到同名表,以及一个年龄段的“age”列。 I'm now interested in the following problem: 我现在对以下问题感兴趣:

In the course of my application, there emerge two queries: 在我的申请过程中,出现了两个问题:

q1 = session.query(User).filter(lots of conditions)
q2 = session.query(User).filter(lots of other conditions)

I now want to "join" q2 onto q1 upon the condition that they have the same age. 我现在想在q1上加入q2,条件是它们具有相同的年龄。 But I have no idea of how this might work. 但我不知道这可能如何运作。 I tried the following without success: 我尝试了以下但没有成功:

q1.join(q2.subquery(), q1.age==q2.age) # the query doesn't hold the columns of the queried class
q1.join(Age).join(q2.subquery()) # Works only if age is a relationship with mapped class Age

My closest calls were something like this: 我最近的电话是这样的:

a1 = aliased(User)
a2 = aliased(User)
q1 = session.query(a1)
q2 = session.query(a2)
s = q2.subquery()
q1.join(s, a1.age==a2.age).all()
>>> sqlalchemy.exc.OperationalError: (OperationalError) no such column: user_2.age 'SELECT user_1.id AS user_1_id, user_1.name AS user_1_name, user_1.age AS user_1_age \nFROM user AS user_1 JOIN (SELECT user_2.id AS id, user_2.name AS name, user_2.age AS age \nFROM user AS user_2) AS anon_1 ON user_1.age = user_2.age' ()

Any ideas about how to make this run? 有关如何运行的任何想法?

After fiddling around and reading answers to questions about subqueries, I managed to find a solution. 在摆弄并阅读有关子查询的问题的答案后,我设法找到了解决方案。 Instead of the last, offending line, put: 而不是最后一个违规行,放:

q1.join(s, a1.age==s.columns.age).all()

That way, the on-clause becomes ON user_1.age = anon_1.age , which is what we want. 这样,on-clause变为ON user_1.age = anon_1.age ,这就是我们想要的。

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

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