我的SQL查询无法在多个房间预订中获得低成本的房间

时间:2013-02-04 13:02:24

标签: mysql sql

贝娄是我的"房间" mysql表。 (这是我创建的示例表,在这里显示。)

enter image description here

我想展示低成本的房间,以防多个房间预订。例如:用户选择了两个房间,第一个房间有1个成人,第二个房间有2个成人。现在我的结果应该如下所示

enter image description here

我的查询是: SELECT * FROM rooms WHERE hotel_code =" 100" GROUP BY成人+儿童按成本排序ASC

它不起作用。我无法通过此查询获得预期的结果。请让我知道解决方案。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT  r.*
FROM Rooms r
INNER JOIN
(
  SELECT 
    adult, child, MIN(Cost) MinCost
  FROM Rooms
  WHERE hotel_code = 100
  GROUP BY  adult, child
) m ON r.adult = m.adult AND r.child = m.child
  AND r.cost = m.mincost
ORDER BY r.id
LIMIT 2;

SQL Fiddle Demo

这会给你:

| ID | HOTEL_CODE |    ROOM_TYPE | ADULT | CHILD | COST |
---------------------------------------------------------
|  2 |        100 | Single Delux |     1 |     0 |   20 |
|  3 |        100 | Twin Stadard |     2 |     0 |   25 |

答案 1 :(得分:1)

用一种(不太可扩展的)扩展来扩展Mahmoud的想法......

SELECT a.*
  FROM
     ( SELECT x.* 
         FROM rooms x 
         JOIN 
            ( SELECT hotel_code
                   , adult
                   , child
                   , MIN(cost) min_cost 
                FROM rooms 
               GROUP 
                  BY hotel_code
                   , adult
                   , child
            ) y 
           ON y.hotel_code = x.hotel_code 
          AND y.adult = x.adult 
          AND y.child = x.child 
          AND y.min_cost = x.cost
     ) a
  LEFT
  JOIN
     ( SELECT x.* 
         FROM rooms x 
         JOIN 
            ( SELECT hotel_code
                   , adult
                   , child
                   , MIN(cost) min_cost 
                FROM rooms 
               GROUP 
                  BY hotel_code
                   , adult
                   , child
            ) y 
           ON y.hotel_code = x.hotel_code 
          AND y.adult = x.adult 
          AND y.child = x.child 
          AND y.min_cost = x.cost
     ) b
    ON b.hotel_code = a.hotel_code
   AND b.adult = a.adult
   AND b.child = a.child
   AND b.cost = a.cost
   AND b.id < a.id
 WHERE b.id IS NULL;