Home > Database > Mysql Tutorial > How Can I Retrieve MySQL Query Results as a Comma-Separated List?

How Can I Retrieve MySQL Query Results as a Comma-Separated List?

Linda Hamilton
Release: 2025-01-17 02:13:10
Original
961 people have browsed it

How Can I Retrieve MySQL Query Results as a Comma-Separated List?

Get MySQL query results as a comma separated list

In MySQL, you may need to retrieve the query results as a comma separated list. Although you can use subqueries to extract specific information, you will encounter some limitations when it comes to presenting the data in the desired format.

Question:

Consider the following query:

<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>
Copy after login

The subquery returns each site name as a separate column, which does not match the desired comma separated list result.

Solution:

MySQL provides the GROUP_CONCAT function to achieve this goal. By leveraging this function, you can modify your query as follows:

<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>
Copy after login

GROUP_CONCAT Concatenates the values ​​in the specified column (in this case, the "name" column in the "sites" table) and separates them with a predefined delimiter (usually a comma). The results are then grouped by the "id" and "name" columns in the "publications" table, providing a unique record for each publication and its associated sites, which are displayed as a comma-separated list.

The above is the detailed content of How Can I Retrieve MySQL Query Results as a Comma-Separated List?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template