假设我有两个表,例如:
table_1:
+----+-------+------------+--
| id | name | table_2_id | ...
+----+-------+------------+--
| 1 | test1 | 2 | ...
| 2 | test2 | 1 | ...
| 3 | test3 | 1 | ...
...
和
table_2:
+----+------+--
| id | name | ...
+----+------+--
| 1 | xxx | ...
| 2 | yyy | ...
| 3 | zzz | ...
...
现在我要从table_2
中选择所有内容,并在每个单元格中添加另一列,其中包含table_1
所有名称的集合,其中table_2_id
与当前id
对应table_2
:
output:
+----+------+-----+--------------+
| id | name | ... | link |
+----+------+-----+--------------+
| 1 | xxx | ... | test2, test3 |
| 2 | yyy | ... | test1 |
| 3 | zzz | ... | % |
...
我怎样才能做到这一点?
答案 0 :(得分:0)
这可以使用correlated subquery来完成。 要合并多行的值,请使用group_concat:
SELECT id,
name,
(SELECT group_concat(name)
FROM table_1
WHERE table_2_id = table_2.id
) AS link
FROM table_2;