简体   繁体   中英

MySQL - How to join two tables without duplicates?

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

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)

您可以使用GROUP_CONCAT

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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