【问题标题】:count subquery in sqlalchemy在 sqlalchemy 中计算子查询
【发布时间】: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;

【问题讨论】:

标签: python sql postgresql sqlalchemy


【解决方案1】:

这篇文章实际上回答了我的问题。我最初搜索时一定错过了它。下面是我的解决方案。

Generate sql with subquery as a column in select statement using SQLAlchemy

store_count = session.query(func.count(Table2.id)).filter(Table2.store_id == Table1.store_id)

session.query.add_columns(Table1.id, Table1.name, Table1.store_id, store_count.label("store_count"))

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2019-07-07
    • 2013-07-05
    • 2019-04-23
    相关资源
    最近更新 更多