dongzhuo1880 2014-04-12 19:25
浏览 49
已采纳

MySQL将多行查询连接到一列

Table structure

client_commands (the "main" table):
id | completed

command_countries:
id | command_id | country_code

command_os:
id | command_id |OS

command_id on references the id column on client_commands.

Problem

I can add client commands with filters based on countries and operating systems. To try and normalise my DB structure, for each new command added:

  • Add a new row to client_commands
  • For each country, I add a new row to command_countries, each referencing client_command.id
  • For each OS, I add a new row to command_os, each referencing client_command.id

For one of the pages on my site, I need to display all client_commands (where completed = 0) as well as all the countries and operating systems for that command. My desired output would be something like:

id | countries | OS
1  | GB, US, FR| 2, 3
2  | ES, HU    | 1, 3

I'm not sure how to go about doing this. The current query I'm using returns multiple rows:

SELECT a.id, b.country_code, c.OS
FROM client_commands a
LEFT JOIN command_countries b on b.command_id = a.id
LEFT JOIN command_os c on c.command_id = a.id
WHERE a.completed = 0

Query results

Any help?

Thanks!

EDIT: I forgot to mention (if you couldn't infer from above) - there can be a different number of operating systems and countries per command.

--

Also: I know I could do this by pulling all the commands, then looping through and running 2 additional queries for each result. But if I can, I'd like to do it as efficiently as possible with one query.

  • 写回答

1条回答 默认 最新

  • dqybjj3497 2014-04-12 19:30
    关注

    You can do this in one query by using GROUP_CONCAT

    SELECT a.id, 
    GROUP_CONCAT(DISTINCT b.country_code SEPARATOR ' ,') `countries`, 
    GROUP_CONCAT(DISTINCT  c.OS SEPARATOR ' ,') `os`, 
    FROM client_commands a
    LEFT JOIN command_countries b on b.command_id = a.id
    LEFT JOIN command_os c on c.command_id = a.id
    WHERE a.completed = 0
    GROUP BY a.id
    

    if you want the ordered results in in a row you can use ORDER BY in GROUP_CONCAT like

    GROUP_CONCAT(b.country_code ORDER BY b.command_id DESC SEPARATOR ' ,') `countries`
    

    But be aware of that fact it has a limit of 1024 character to concat set by default but this can be increased b,steps provided in manual

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄