MySQL - 如何连接两个表而不重复?
我有两个表,如下所示
hotels
------
hotelID
hotelName
第二个表
operators
---------
opID
opName
opServices
opHotelID
是一个简短的解释:在第一个表中,我有很多酒店,它们的增量 ID 是唯一的。第二个表包含为该酒店提供附加服务的所有运营商。这里的opID也是唯一的,但是opHotelID存在多次,因为可能有很多运营商提供酒店。
现在,我想要得到的是以下内容:
我想要获取 HotelName 和一个附加列(称为 Operators),其中列出了提供酒店的所有运营商。
所以结果应该是这样的...
123 - Hotel ABC - OP1,Op2,OP3
而不是这样...
123 - Hotel ABC - OP1
123 - HOtel ABC - OP2
123 - Hotel ABC - OP3
有没有一种方法可以在一个 SQL 查询中做到这一点,或者你将如何解决这个问题?我目前正在开发一个搜索功能,目前我有一个带有左连接的简单 SELECT 查询,但这会返回更多行。现在,搜索应该只显示唯一的 HotelID,并将不同的运营商组合在一列中。
感谢您的帮助,祝您有美好的一天...
再见 世界西尼亚
I have two tables like the following
hotels
------
hotelID
hotelName
Second table
operators
---------
opID
opName
opServices
opHotelID
a short explanation: In the first table I have a lot of hotels which have an increment id which is unique. The second table contains all the operators offering this hotel with additional services. The opID here is unique too but the opHotelID exists multiple times, because there can be many operators offering the hotel.
Now, what I want to get is the following:
I want to get the HotelName and an additional Column (called Operators) which lists all the operators offering the hotel.
So the result should be like this...
123 - Hotel ABC - OP1,Op2,OP3
instead of this...
123 - Hotel ABC - OP1
123 - HOtel ABC - OP2
123 - Hotel ABC - OP3
Is there a way to do this in one SQL query or how would you solve this problem? I am currently working on a search function and currently i have a simple SELECT query with a left join but this returns a lot of more rows. Now the Search should only display unique HotelIDs and combine the different Operators in one column.
Thanks for you help and have a nice day...
Bye
WorldSignia
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
如果你想知道操作员的数量,你必须在操作员 ID 上使用 COUNT,如下所示:
Try this one:
If you want to have the number of operators, you have to use COUNT on the operators ID like that:
您可以使用 GROUP_CONCAT
You can use GROUP_CONCAT
您应该有一个简单的链接表,这将为许多运营商与酒店创建多对多关系
you should have a simple link table, this will create the many to many relationship for many operators to a hotel
如果您不想更改数据库设计,则可以使用此查询
,否则创建一个映射表,产生
多对多
关系if you dont want to change your DB design, you can use this query
otherwise, create a mapping table resulting the
many to many
relation您应该按照已经建议的方式使用 GROUP_CONCAT 。这是查询:
You should use GROUP_CONCAT as already suggested. Here's the query: