mysql连接查询来自两个表的选择行,其中一个表具有与第一个表匹配的多个行

时间:2014-06-20 03:35:10

标签: php mysql join

enter image description here

要在图像中获得结果,我现在正在使用此查询

select h.*, group_concat(distinct room_type) as RoomTypes
from hotel h 
left join rooms r on h.hotel_id = r.hotel_id
group by h.hotel_id;

但此查询仅返回归档的房间类型。但我需要该表中的所有列。

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

沿着这些方向尝试一些事情。它假定可能有一个房间有wifi但没有早餐和所有其他组合。

SELECT h.*, SUM(r,availability) + ' rooms ' + 
            CASE WHEN r.wifi = 1 THEN ' with wifi ' ELSE '' END +
            CASE WHEN r.breakfast = 1 THEN ' with breakfast' ELSE '' END
            as RoomInfo
FROM hotel h 
LEFT JOIN rooms r ON h.hotel_id = r.hotel_id
GROUP BY h.hotel_id, r.room_type, r.wify, r.breakfast
HAVING SUM(r.availability) > 0;

前端需要处理好的格式。

答案 1 :(得分:1)

尝试执行sql

select h.*, CONCAT_WS(' ', r.availability, room_type, 'rooms', IF(r.wifi = 1 AND r.breakfast = 1,'with wifi and breakfast',IF(r.wifi = 1 ,'with wifi','with breakfast'))) AS Attributes
from hotels as h
inner join rooms as r on r.hotel_id = h.id
group by h.id, r.room_type, r.wifi, r.breakfast HAVING SUM(r.availability) > 0;