MySQL - How to join two tables without duplicates?

醉酒当歌 提交于 2019-12-02 03:57:09

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)

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

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