?yb? 2008-11-10 02:34 采纳率: 100%
浏览 242
已采纳

我可以将多个 MySQL 行连接到一个字段吗?

Using MySQL, I can do something like:

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

My Output:

shopping
fishing
coding

but instead I just want 1 row, 1 col:

Expected Output:

shopping, fishing, coding

The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.

I've looked for a function on MySQL Doc and it doesn't look like the CONCAT or CONCAT_WS functions accept result sets, so does anyone here know how to do this?

转载于:https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field

  • 写回答

9条回答 默认 最新

  • ?yb? 2012-03-06 16:16
    关注

    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, you can add the DISTINCT operator to avoid duplicates:

    SELECT person_id, GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
    FROM peoples_hobbies 
    GROUP BY person_id;
    

    As Jan stated in their comment, you can also sort the values before imploding it 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, there is a 1024 byte limit on the result. To solve this, run this query before your query:

    SET group_concat_max_len = 2048;
    

    Of course, you can change 2048 according to your needs. To calculate and assign the value:

    SET group_concat_max_len = CAST(
        (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
        FROM peoples_hobbies 
        GROUP BY person_id)
        AS UNSIGNED
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)