社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Muhammad Shahzad

Muhammad Shahzad 最近回复了
5 年前
回复了 Muhammad Shahzad 创建的主题 » MySQL-如何将行连接成一个[重复]

你可以用 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);