你可以用
GROUP_CONCAT
:
SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
正如路德维希在
his comment,
您可以添加
DISTINCT
操作员要避免重复:
SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
正如Jan在
their comment,
也可以在使用
ORDER BY
:
SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
正如Dag在
his comment,
结果有1024字节的限制。要解决此问题,请在查询之前运行此查询:
SET group_concat_max_len = 2048;
当然,你可以改变
2048
根据你的需要。要计算并分配值,请执行以下操作:
SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);