search

Home  >  Q&A  >  body text

Is it possible 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 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粉556159786P粉556159786519 days ago521

reply all(2)I'll reply

  • P粉366946380

    P粉3669463802023-08-23 12:03:30

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

    reply
    0
  • P粉002023326

    P粉0020233262023-08-23 10:26:52

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

    reply
    0
  • Cancelreply