MySQL 结果为逗号分隔列表

2021-11-20 00:00:00 sql concatenation mysql

我需要运行如下查询:

SELECT p.id, p.name, 
       (SELECT name 
          FROM sites s 
         WHERE s.id = p.site_id) AS site_list
  FROM publications p

但我希望子选择返回一个逗号分隔的列表,而不是一列数据.这甚至可能吗,如果可以,怎么办?

But I'd like the sub-select to return a comma separated list, instead of a column of data. Is this even possible, and if so, how?

推荐答案

您可以使用 GROUP_CONCAT 来执行,例如类似的东西

You can use GROUP_CONCAT to perform that, e.g. something like

SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;

相关文章