来自4个表的复杂sql查询

时间:2012-01-28 11:17:44

标签: sql count left-join min

我正在开发一个有很多酒店的在线旅游指南。每个酒店属于特定类别,有很多房型,每个酒店房间每季都有不同的价格。我想从4个表格中进行复杂的查询,以获得每个酒店类别的酒店总数其中每个酒店客房的最低价格在2个值之间,由滑块调整

我的表格如下:

  • 类别
  • id_category
  • CATEGORY_NAME

  • 酒店
  • id_hotel
  • HOTEL_NAME
  • CATEGORY_ID
  • ......

  • hotels_room_types
  • id_hotels_room_type
  • HOTEL_ID
  • room_type_id
  • ......

  • hotels_room_types_seasons
  • hotels_room_types_id
  • season_id
  • ......

例如category_name的一些值是:酒店,公寓,旅馆
我希望我的结果表有两个字段,如下所示:

酒店32
公寓0
旅馆5


我尝试了以下查询,但它返回了每个类别所有酒店的总数,而不是房间最低价格在价格范围之间的酒店数量。

SELECT c.category_name, count( DISTINCT id_hotel ) , min( price ) min_price
FROM categories c
LEFT JOIN hotels w ON ( c.id_category = w.category_id ) 
LEFT JOIN (
hotels_room_types
INNER JOIN hotels_room_types_seasons ON hotels_room_types.id_hotels_room_types = hotels_room_types_seasons.hotels_room_types_id) 
ON w.id_hotel = hotels_room_types.hotel_id
GROUP BY c.category_name
HAVING min_price >=10 AND min_price <=130

有人可以帮我写出适当的查询吗? 感谢!!!

2 个答案:

答案 0 :(得分:1)

SELECT  Categories.Name, COUNT(DISTINCT ID_Hotel) [Count]
FROM    Hotels
        INNER JOIN Categories
            ON Category_ID = ID_Category
        INNER JOIN
        (   SELECT  Hotel_ID, MIN(Price) [LowestPrice]
            FROM    hotels_room_types
                    INNER JOIN hotels_room_types_seasons
                        ON id_hotels_room_type = hotels_room_types_id
            -- CONSIDER FILTERING BY SEASON HERE
            GROUP BY Hotel_ID
        ) price
            ON price.Hotel_ID = Hotels.ID_Hotel
WHERE   LowestPrice BETWEEN 10 AND 130 -- OR WHATEVER YOUR PARAMETERS ARE
GROUP BY Categories.Name

我不知道您使用的是哪种RDBMS,但我不知道您的查询在哪里工作。您对Min Price(我假设)的问题是因为您在按类别分组后应用逻辑,因此您计算所有类别的最低价格在10到130之间的酒店,而不是酒店有房间的地方最低价格在10到130之间。

答案 1 :(得分:0)

select
      c.Category_name,
      count(*) NumHotels
   from
      ( select distinct
              byRoomType.hotel_id
           from
              hotels_room_types_seasons bySeason
                 join hotels_room_types byRoomType
                    on bySeason.hotels_room_types_id = byRoomType.id_hotels_room_type
           where
              bySeason.Price between LowPriceParameter and HighPriceParameter 
      ) QualifiedHotels

         join Hotels
            on QualifiedHotels.hotel_id = Hotels.id_hotel

            join Categories c
               on category_id = c.id_category