Sql 完全外连接查询在 SQLAlchemy 中不起作用

Posted

技术标签:

【中文标题】Sql 完全外连接查询在 SQLAlchemy 中不起作用【英文标题】:Sql Full outer join query does not work in SQLAlchemy 【发布时间】:2021-03-26 11:09:31 【问题描述】:

我有 sql 查询,我正在尝试执行完全外部联接,这在 SQL 中可以正常工作,但在 Alchemy 中不起作用。

Select

Table1.field1 as Table1Field1, Table1.field2 as Table1Field2, 
Table2.field1 as Table2Field1, Table2.field2 as Table2Field2, 
Table3.field1 as Table3Field1, Table3.field2 as Table3Field2, 
Table4.field1 as Table4Field1, Table4.field2 as Table4Field2, 
Table5.field1 as Table5Field1, Table5.field2 as Table5Field2, 
Table7.field1 as Table7Field1, Table7.field2 as Table7Field2 


From Table1

full outer JOIN Table2 ON Table2.T1_id = Table1.id 
full outer JOIN Table3 ON Table3.T1_id = Table1.id 
full outer JOIN Table5 ON Table5.T1_id = Table1.id 
full outer JOIN Table4 ON Table4.id = Table5.T4_id
full outer JOIN Table7 ON Table7.id = Table5.T7_id;

T1_id是Table1.id的所有表中的外键

但是我在下面尝试的查询我不断得到

    Please use the .select_from() method to establish an explicit left side, as well as 
providing an explcit ON clause if not present already to help resolve the ambiguity.

我尝试过的查询

session.query(Table1).join(Table2, Table3, Table4, Table5, Table7).
filter(Table2.T1_id = Table1.id, Table3.T1_id = Table1.id, Table4.T1_id =Table1.id, Table4.T5_id= Table5.id, Table4.T7_id = Table7.id).all()

我想要 sqlAlchemy 版本,我可以在其中获得 sql 查询中给出的完整外连接。

More detailed error


 "help resolve the ambiguity." % (right,)
sqlalchemy.exc.InvalidRequestError: Don't know how to join to <class 'model.Table4'>. Please use the .select_from() method to establish an explicit left side, as well as providing an explcit ON clause if not present already to help resolve the ambiguity.

【问题讨论】:

删除选择列表末尾的逗号 @Serg 完成,抱歉错过了 你能用两张表重现这个问题吗? 见***.com/questions/20361017/… 上一条评论中引用的答案很老,所以也要注意follow-up comment。 【参考方案1】:
session.query(Table1).join(Table2, Table3, Table4, Table5, Table7).
filter(Table2.id = Table1.id, Table3.id = Table1.id, Table4.id = Table5.id, Table7.id = Table5.id).all()

我上面查询Table1、Table2和Table3是连通的,Table4、Table5 Table7是连通的但是这两组表之间没有关联。

这是一本好书: https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.join.params.full

请在所有表之间建立连接,然后添加full=true

    session.query(Table1).join(Table2, Table3, Table4, Table5, Table7).
        filter(Table2.id = Table1.id, Table3.id = Table1.id, 
Table4.T1.id = Table1.id, Table4.id = Table5.id, Table7.id = Table5.id,full=true).all()

【讨论】:

table1、table2或table3与table4、table5或table7之间是否存在关系? 是的,table5,7 和 table 4,table 2,3,4 和 table1 Table4.id=Table1.id? 是Table4.T1.id = Table1.id 虽然我不确定,但请尝试我的修改答案。

以上是关于Sql 完全外连接查询在 SQLAlchemy 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Flask-SQLAlchemy 左外连接过滤查询

sqlalchemy 和双外连接

如何在 Sqlalchemy 中正确使用 SQL 连接/子查询

SQL多表连接查询

SQL多表查询

SQL多表连接查询(详细实例)