MySQL Results as comma separated list

Glen Solsberry picture Glen Solsberry · Mar 19, 2009 · Viewed 151k times · Source

I need to run a query like:

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?

Answer

Paul Dixon picture Paul Dixon · Mar 19, 2009

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;