douyin8809 2013-11-17 16:32
浏览 213
已采纳

使用INNER JOIN显示多个结果

I have these three MySQL tables:

companies                    services                      auxiliary
id_company name_company      id_service  name_service      id_company id_service   

1          Google            1           Search            1          1   
2          Yahoo             2           Calendar          1          2  
                             3           Mail              1          3
                             4           Maps              1          4
                                                           2          1
                                                           2          3

I am wondering if I could display with only one query (I'm using php):

Google: Search, Calendar, Mail, Maps.
Yahoo: Search, Mail.

Now what I am doing is display the companies, and for each company I make another MySQL query to display the services. Is it possible to do that with only one query? Thank you.

  • 写回答

2条回答 默认 最新

  • dragam0217 2013-11-17 16:38
    关注

    The answer to your question is: "Yes".

    Oh, you want to know how to do it as well. The key is to join the tables together and then aggregate at the company level. I am going to assume that you really want the output as two columns (company name, services), rather than one string with them concatenated together.

    The SQL is:

    select c.name_company, group_concat(s.name_service separator ', ') as services
    from auxiliary a join
         companies c
         on a.id_company = c.id_company join
         services s
         on a.id_service =  s.id_service
    group by c.id_company, c.name_company;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝