使用 SQLAlchemy 核心获取连接 table 的列
Getting columns of the joined table using SQLAlchemy core
我有三个 table,table1
包含两个外键,分别指向 table2
和 table3
。
我运行以下语句使用SQLAlchemy核心
stmt = select(self._table1).join(
self._table2).join(self._table3)
res = self._connection.execute(stmt)
那是给我整行 table1
。
这不是应该获取其他两个 table 的列吗?如何获得?
底层驱动是sqlite3。
编辑 1:
sqlite3 似乎不支持完全连接,但我应该可以通过将 UNION ALL
与另一个 table 上的 LEFT JOIN
组合来获得相同的结果 table =20=]
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
除了进行两次查询之外,还有其他解决方法吗?
在 select
中执行 joins:
select(t1.join(t2).join(t3))
这将 select 所有三个表中的所有列。
到 select 特定列,在 select
中指定所需的列并在 select_from
:
中进行连接
select(t1.c.col1, t2.c.col2, t3.c.col3).select_from(t1.join(t2).join(t3))
我有三个 table,table1
包含两个外键,分别指向 table2
和 table3
。
我运行以下语句使用SQLAlchemy核心
stmt = select(self._table1).join(
self._table2).join(self._table3)
res = self._connection.execute(stmt)
那是给我整行 table1
。
这不是应该获取其他两个 table 的列吗?如何获得?
底层驱动是sqlite3。
编辑 1:
sqlite3 似乎不支持完全连接,但我应该可以通过将 UNION ALL
与另一个 table 上的 LEFT JOIN
组合来获得相同的结果 table =20=]
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
除了进行两次查询之外,还有其他解决方法吗?
在 select
中执行 joins:
select(t1.join(t2).join(t3))
这将 select 所有三个表中的所有列。
到 select 特定列,在 select
中指定所需的列并在 select_from
:
select(t1.c.col1, t2.c.col2, t3.c.col3).select_from(t1.join(t2).join(t3))