MySQL - How to join two tables without duplicates?

断了今生、忘了曾经 提交于 2019-12-09 03:46:16

问题


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


回答1:


Try this one:

SELECT hotels.hotelID, 
hotels.hotelName,
GROUP_CONCAT(operators.opName SEPARATOR ', ') AS opList
FROM hotels
INNER JOIN operators 
ON operators.opHotelID = hotels.hotelID
GROUP BY(hotels.hotelID)

If you want to have the number of operators, you have to use COUNT on the operators ID like that:

SELECT hotels.hotelID, 
hotels.hotelName,
GROUP_CONCAT(operators.opName SEPARATOR ', ') AS opList,
COUNT(operators.opID) AS nbOperatos
FROM hotels
LEFT JOIN operators 
ON operators.opHotelID = hotels.hotelID
GROUP BY(hotels.hotelID)



回答2:


You can use GROUP_CONCAT




回答3:


you should have a simple link table, this will create the many to many relationship for many operators to a hotel

operatorhotels
---------
opID
opHotelID



回答4:


if you dont want to change your DB design, you can use this query

SELECT hotelID,hotelName,opName FROM hotels h
INNER JOIN operators o ON  h.hotelID = o.opHotelID
GROUP BY h.hotelID,hotelName,opName 

otherwise, create a mapping table resulting the many to many relation




回答5:


You should use GROUP_CONCAT as already suggested. Here's the query:

SELECT h.hotelID, h.hotelName, GROUP_CONCAT(o.opName) 
FROM hotels h
INNER JOIN operators o ON h.hotelID = o.opHotelID
GROUP BY h.hotelID


来源:https://stackoverflow.com/questions/7566636/mysql-how-to-join-two-tables-without-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!