我正试图弄清楚如何在SQLAlchemy中复制以下查询
SELECT c.company_id AS company_id,
(SELECT policy_id FROM associative_table at WHERE at.company_id = c.company_id) AS policy_id_ref,
(SELECT `default` FROM policy p WHERE p.policy_id = policy_id_ref) AS `default`,
FROM company c;
请注意,这是我正在处理的基本示例。实际的模式支持数据和关系版本控制,这需要子查询包含附加条件,排序和限制,使它们不可能(如果不是不可能)加入。
问题的关键在于第二个子查询如何依赖policy_id_ref - 从第一个子查询获得的值。在SQLAlchemy中,这实际上就是我现在所拥有的:
ct = aliased(classes.company)
at = aliased(classes.associative_table)
pt = aliased(classes.policy)
policy_id_ref = session.query(at.policy_id).\
filter(at.company_id == ct.company_id).\
label('policy_id_ref')
policy_default = session.query(pt.default).\
filter(pt.id == 'policy_id_ref').\
label('default')
query = session.query(ct.company_id,policy_id_ref,policy_default)
“company”表的提取工作正常,检索“policy_id_ref”列的第一个子查询也是如此。问题是必须引用“policy_id_ref”列的第二个子查询。我不知道如何编写其过滤器,以便在结果查询中实际呈现“policy_id_ref”,以匹配第一个子查询的标签。
建议?
提前致谢