Home >Database >Mysql Tutorial >How to Convert Multiple Values from a Column into a Comma Separated String in MySQL?

How to Convert Multiple Values from a Column into a Comma Separated String in MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 17:40:02864browse

How to Convert Multiple Values from a Column into a Comma Separated String in MySQL?

Converting Selected Values to Comma Separated String in MySQL

It is often useful to convert selected values from a database table into a comma separated string. This can be done using the GROUP_CONCAT() function.

Problem Statement:

The goal is to convert the selected values of the id column from the table_level table, where parent_id is 4, into a single comma separated string.

Initial Code:

<code class="sql">SELECT id
FROM table_level
WHERE parent_id = 4;</code>

Desired Output:

"5,6,9,10,12,14,15,17,18,779"

Solution:

To achieve this, use the following query:

<code class="sql">SELECT GROUP_CONCAT(id)
FROM table_level
WHERE parent_id = 4
GROUP BY parent_id;</code>

Explanation:

  • The GROUP_CONCAT() function concatenates the values of the specified column, id in this case, for each unique value of the specified group by column, parent_id in this case.
  • The result is a single comma separated string containing all the values of the id column for the specified parent_id.

The above is the detailed content of How to Convert Multiple Values from a Column into a Comma Separated String in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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