选择房间,价格最低的城市

时间:2011-04-13 13:40:39

标签: mysql group-by

我有3个餐厅,酒店,城市,如何选择价格最低的房间和每个城市的hotel_id

price | hotel_id | city_id
10    | 1        | 1
13    | 4        | 2
44    | 7        | 3 
...

SELECT MIN(price) price, hotel_id, city_id FROM (
 SELECT MIN(room_price1) price, hotel_id, city_id 
    FROM Hotel 
    JOIN  Room USING(hotel_id)
        JOIN City USING(city_id)
    LEFT JOIN Service_hotel_option USING (hotel_id)
    WHERE room_price1 > 0
        GROUP BY hotel_id
    ORDER BY price ASC) t 
GROUP BY city_id
ORDER by city_name, price

但我不确定。

1 个答案:

答案 0 :(得分:1)

怎么样:

SELECT price, hotel_id, city_id
FROM hotel
INNER JOIN room AS r1 USING (hotel_id)
WHERE NOT EXISTS (SELECT 1 FROM room AS r2
    WHERE r2.hotel_id = r1.hotel_id AND r2.price < r1.price)

如果找不到价格较低的房间,则只会从hotel INNER JOIN room中选择行。