How to concatenate multiple MySQL rows into one field?
P粉482108310
P粉482108310 2023-08-28 11:10:23
0
2
423
<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 1 row, 1 column: </p> <p><strong>Expected 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 much more rows than I want. </p> <p>I looked up a function on the MySQL Doc and it doesn't look like the <code>CONCAT</code> or <code>CONCAT_WS</code> functions accept a result set. </p> <p>Does anyone here know how to do this? </p>
P粉482108310
P粉482108310

reply all(2)
P粉520545753

See GROUP_CONCAT if your version of MySQL (4.1) supports it. For more information, see DocumentationDetails.

It looks like:

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

You can use GROUP_CONCAT:

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

As Ludwig stated in his comment, a> 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, a> you can also sort the values ​​before imploding 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, the result has a limit of 1024 bytes. To resolve this issue, run this query before querying:

SET group_concat_max_len = 2048;

Of course, you can change 2048 as needed. Calculate and assign values:

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