P粉5205457532023-08-29 09:04:00
看看 GROUP_CONCAT
如果您的 MySQL 版本 (4.1) 支持它。有关更多信息,请参阅文档详细信息。
它看起来像:
SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') FROM peoples_hobbies WHERE person_id = 5 GROUP BY 'all';
P粉0418569552023-08-29 00:29:10
您可以使用GROUP_CONCAT< /代码>
:
SELECT person_id, GROUP_CONCAT(hobbies SEPARATOR ', ') FROM peoples_hobbies GROUP BY person_id;
正如路德维希在他的评论中所述, a> 您可以添加 DISTINCT
运算符以避免重复:
SELECT person_id, GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ') FROM peoples_hobbies GROUP BY person_id;
正如 Jan 在他们的评论中所述, a> 您还可以在使用 ORDER BY
内爆之前对值进行排序:
SELECT person_id, GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ') FROM peoples_hobbies GROUP BY person_id;
正如达格在他的评论中所述, 结果有 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);