Is it possible to concatenate multiple MySQL rows into one field?
P粉556159786
P粉556159786 2023-08-22 14:02:48
0
2
516
<p>Using <code>MySQL</code>, I can do the following: </p> <pre class="brush:php;toolbar:false;">SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;</pre> <p><strong>My output: </strong></p> <pre class="brush:php;toolbar:false;">shopping fishing coding</pre> <p>But I only want one row and one column: </p> <p><strong>Desired output: </strong></p> <pre class="brush:php;toolbar:false;">shopping, fishing, coding</pre> <p>The reason is that I'm selecting multiple values ​​from multiple tables, and after all the joins, I'm getting more rows than I want. </p> <p>I looked up a function in the MySQL documentation and it looks like the <code>CONCAT</code> or <code>CONCAT_WS</code> functions don't accept a result set. </p> <p>So does anyone here know how to do this? </p>
P粉556159786
P粉556159786

reply all(2)
P粉366946380

If your MySQL version (4.1) supports it, you can check GROUP_CONCAT. Please refer to Documentation for more details.

The query statement is as follows:

SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') 
  FROM peoples_hobbies 
  WHERE person_id = 5 
  GROUP BY 'all';
P粉002023326

You can use the GROUP_CONCAT function:

SELECT person_id,
   GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Ludwig mentioned in his comment, you can add the DISTINCT operator to avoid duplication:

SELECT person_id,
   GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Jan mentioned in their comment, you can also sort the values ​​before merging, using ORDER BY :

SELECT person_id, 
       GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

As Dag stated in his comment, there is a 1024 byte limit on the result. To resolve this issue, run the following query before your query:

SET group_concat_max_len = 2048;

Of course, you can change the value of 2048 as needed. Here's how to calculate and assign a value:

SET group_concat_max_len = CAST(
                     (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
                           FROM peoples_hobbies
                           GROUP BY person_id) AS UNSIGNED);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template