首页 > 解决方案 > 使用 SQLAlchemy 核心获取连接表的列

问题描述

我有三个表,table1包含两个外键,它们是指table2table3。我正在使用 SQLAlchemy 核心运行以下语句

stmt = select(self._table1).join(
            self._table2).join(self._table3)
res = self._connection.execute(stmt)

那是给我整排的table1

那不是应该获取其他两个表的列吗?如何得到它们?

底层驱动程序是 sqlite3。

编辑1:

似乎 sqlite3 不支持完全连接,但我应该能够通过像这样与另一张表上的UNION ALLa组合来获得相同的结果LEFT JOIN

select(self._table1).join(self._table2).union_all(select(self._table2).where(self._table2.c._id=="id"))

SQLAlchemy 现在给了我

sqlalchemy.exc.CompileError: All selectables passed to CompoundSelect must have identical numbers of columns; select #1 has 11 columns, select #2 has 3

除了进行两个查询之外的任何解决方法?

标签: pythonsqlitejoinselectsqlalchemy

解决方案


做里面的连接select

select(t1.join(t2).join(t3))

这将选择所有三个表中的所有列。

要选择特定的列,请在 中指定所需的列select并在 a 中进行连接select_from

select(t1.c.col1, t2.c.col2, t3.c.col3).select_from(t1.join(t2).join(t3))

推荐阅读