SQL 连接子查询
SQL Concat Subquery
我希望 "user_names" 成为用户列表,但我无法将多个子查询项分配给 "user_names"。如果子查询只有 returns 1 个项目,它就可以工作,但如果它 returns 多个就不起作用。
床Table
[id]
[1]
[2]
[3]
作业Table:
[id, bed_id, user_id]
[1, 1, 1]
[2, 1, 2]
用户Table:
[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']
您的查询存在一个问题,即您按要应用 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;""
我希望 "user_names" 成为用户列表,但我无法将多个子查询项分配给 "user_names"。如果子查询只有 returns 1 个项目,它就可以工作,但如果它 returns 多个就不起作用。
床Table
[id]
[1]
[2]
[3]
作业Table:
[id, bed_id, user_id]
[1, 1, 1]
[2, 1, 2]
用户Table:
[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']
您的查询存在一个问题,即您按要应用 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;""