【发布时间】:2022-01-24 00:55:39
【问题描述】:
我在将子查询转换为 sqlalchemy 时遇到了一些问题。我有两个表,它们都有一个作为外键的 store_id 列(但它不是直接的多对多关系),我需要从表 1 中返回 id、store_id 和名称以及记录数来自表 2 的也具有相同 store_id 的。我知道我将用来返回这些记录的 SQL,我现在才确定如何使用 sqlalchemy。
SELECT
table_1.id
table_1.store_id,
table_1.name,
(
SELECT
count(table_2.id)
FROM
table_2
WHERE
table_1.store_id = table_2.store_id
) AS store_count FROM table_1;
【问题讨论】:
-
您好,感谢您的回复,我对如何在 sqlalchemy 中创建子查询并不感到困惑,只是对如何创建这个特定的子查询感到困惑。
标签: python sql postgresql sqlalchemy