Extracting data in a specific format, like a comma-separated list, is a common task. Let's say you need publication details and a comma-separated list of associated site names. A naive approach using a subquery might look like this:
<code class="language-sql">SELECT p.id, p.name, (SELECT name FROM sites s WHERE s.id = p.site_id) AS site_list FROM publications p</code>
This, however, produces a single site name per row, not a comma-separated list.
The key to creating the desired comma-separated list is the GROUP_CONCAT
function. This function concatenates multiple values into a single string, separated by commas (or a custom separator). Here's the improved query:
<code class="language-sql">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;</code>
This revised query uses GROUP_CONCAT(s.name)
to combine site names. The INNER JOIN
efficiently links publications
and sites
tables, and GROUP BY p.id, p.name
ensures that the GROUP_CONCAT
function aggregates site names correctly for each publication.
The above is the detailed content of How Can I Generate Comma-Separated Lists from MySQL Query Results?. For more information, please follow other related articles on the PHP Chinese website!