Home  >  Q&A  >  body text

How to concatenate multiple MySQL rows into one field?

<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粉482108310P粉482108310419 days ago378

reply all(2)I'll reply

  • P粉520545753

    P粉5205457532023-08-29 09:04:00

    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';

    reply
    0
  • P粉041856955

    P粉0418569552023-08-29 00:29:10

    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, 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 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);

    reply
    0
  • Cancelreply