简体   繁体   English

使用INNER JOIN显示多个结果

[英]Display multiple results with INNER JOIN

I have these three MySQL tables: 我有以下三个MySQL表:

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): 我想知道是否可以只显示一个查询(我正在使用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. 现在,我正在做的是显示公司,并为每个公司执行另一个MySQL查询以显示服务。 Is it possible to do that with only one query? 是否可以只执行一个查询? Thank you. 谢谢。

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: SQL是:

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;

Yes, you could. 是的,你可以。 Although in my opinion the approach you described seems more natural to me. 尽管我认为您描述的方法对我来说似乎更自然。 (Having one query/cursor for the companies, and another one for the services) (对于公司有一个查询/光标,对于服务有另一个查询/光标)

You could use one single query to prepare following list: 您可以使用一个查询来准备以下列表:
Google, Search 谷歌搜索
Google, Calendar Google,日历
Google, Mail 谷歌邮件
Google, Maps 谷歌地图
Yahoo, Search 雅虎,搜索
Yahoo, Mail 雅虎邮箱
... ...
(I have left out the ids for simplicity) (为简单起见,我省略了ID)
Then you run through the list, every time the company changes you begin a new result line. 然后,您遍历该列表,每次公司更改时,您都会开始一个新的结果行。 I find this a bit more complicated than the approach you described. 我发现这比您描述的方法要复杂一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM