Is it possible to concatenate multiple MySQL rows into one field?
P粉556159786
2023-08-22 14:02:48
<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>
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:
You can use the
GROUP_CONCAT
function:As Ludwig mentioned in his comment, you can add the
DISTINCT
operator to avoid duplication:As Jan mentioned in their comment, you can also sort the values before merging, using
ORDER BY
: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:
Of course, you can change the value of
2048
as needed. Here's how to calculate and assign a value: