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