我写了一个mysql的查询,实现了我想要的。它的结构有点像这样:
select * from table_a where exists(
select * from table_b where table_a.x = table_b.x and exists(
select * from table_c where table_a.y = table_c.y and table_b.z = table_c.z
)
)
我将查询翻译成sqlalchemy,结果结构如下:
session.query(table_a).filter(
session.query(table_b).filter(table_a.x == table_b.x).filter(
session.query(table_c).filter(table_a.y == table_c.y).filter(table_b.x == table_c.z).exists()
).exists()
)
生成如下查询:
select * from table_a where exists(
select * from table_b where table_a.x = table_b.x and exists(
select * from table_c, table_a where table_a.y = table_c.y and table_b.z = table_c.z
)
)
请注意在最里面的查询中重新选择table_a
- 这会破坏预期的功能。
如何阻止sqlalchemy在嵌套查询中再次选择表格?