python - 使用 SQLAlchemy 核心获取连接表的列
问题描述
我有三个表,table1
包含两个外键,它们是指table2
和table3
。我正在使用 SQLAlchemy 核心运行以下语句
stmt = select(self._table1).join(
self._table2).join(self._table3)
res = self._connection.execute(stmt)
那是给我整排的table1
。
那不是应该获取其他两个表的列吗?如何得到它们?
底层驱动程序是 sqlite3。
编辑1:
似乎 sqlite3 不支持完全连接,但我应该能够通过像这样与另一张表上的UNION ALL
a组合来获得相同的结果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
除了进行两个查询之外的任何解决方法?
解决方案
做里面的连接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))
推荐阅读
- javascript - 为什么选择在绑定到模型时显示它的第一个元素
- git - 同一用户的 Git 用户权限
- mysql - SQL:根据两个最近关联记录的比较选择记录
- python - 嵌套 Python3 字典有问题
- django - 如何让用户在用户仪表板中编辑自定义用户模型详细信息并在 django 中的模型中进行更新?
- ios - 如何使用 react native firebase 动态链接获取 iOS 的初始链接?
- python - 创建一个返回多年来每小时记录的最大降水值年份的函数?
- python - 如何修复“请求的技能响应有问题”错误?
- image-processing - 检测旋转的车辆图像
- ios - 条件绑定的初始化程序必须具有 Optional 类型,而不是 '[AnyHashable : Any]'