How to concatenate multiple MySQL rows into one field?
P粉482108310
2023-08-28 11:10:23
<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>
See
GROUP_CONCAT
if your version of MySQL (4.1) supports it. For more information, see DocumentationDetails.It looks like:
You can use
GROUP_CONCAT
:As Ludwig stated in his comment, a> you can add the
DISTINCT
operator to avoid duplication:As Jan mentioned in their comment, a> you can also sort the values before imploding using
ORDER BY
:As Dag stated in his comment, the result has a limit of 1024 bytes. To resolve this issue, run this query before querying:
Of course, you can change
2048
as needed. Calculate and assign values: