SQL Concat子查询

时间:2015-08-10 23:41:51

标签: sql postgresql subquery concatenation concat

我想要" user_names"作为用户列表,但我无法将多个子查询项目分配给" user_names"。如果子查询只返回1个项目,则它可以工作,但如果它返回多个项目则不起作用。

床单
[ID]
[1]
[2]
[3]

作业表:
[id,bed_id,user_id]
[1,1,1]
[2,1,2]

用户表:
[id,' user_name']
[1,' John Smith']
[2,' Jane Doe']

    sql = "SELECT
        b.id,
        (
            SELECT
                u.user_name
            FROM
                assignments AS a
            INNER JOIN
                users as u
            ON
                a.user_id = u.id
            WHERE a.bed_id = b.id
        ) AS user_names
        FROM beds AS b"

期望的结果将是:
[1,' John Smith,Jane Doe']
[2,'']
[3,'']

我尝试对床ID进行硬编码并运行此段以获取名称列表。它没有用:

    sql = """
        (
        SELECT
            array_agg(user_name)
        FROM
            roomchoice_assignment AS a
        INNER JOIN
            roomchoice_customuser as u
        ON
            a.user_id = u.id
        WHERE
            a.bed_id = 1
        GROUP BY user_name
        )"""

它返回了以下内容:

[
    [
        [
            "John Smith"
        ]
    ], 
    [
        [
            "Jane Doe"
        ]
    ]
]

我希望这样:

['John Smith, Jane Doe']

1 个答案:

答案 0 :(得分:3)

您遇到的查询存在的一个问题是,您正在按照您正在应用array_agg的列进行分组。如果您删除该组,则会获得"{"John Smith","Jane Doe"}",但您仍然会丢失床ID列,如果您想要所有床的列表,即使没有分配,您也应该使用左连接而不是子查询(这对于性能和可读性也应该更好。)

您可以使用重复问题所指示的string_agg

此查询:

SELECT b.id, string_agg(u.user_name, ', ') users
FROM beds AS b
LEFT JOIN assignment AS a ON a.bed_id = b.id
LEFT JOIN users as u ON a.user_id = u.id
GROUP by b.id;

会给你一个像:

的结果
1;"John Smith, Jane Doe"
2;""
3;""