从另一个表中添加与第一个MySQL查询的结果匹配的列

时间:2010-05-05 03:54:46

标签: mysql

这是我对选择期间可用房间的查询:

SELECT rooms.room_id 
  FROM rooms 
 WHERE rooms.room_id NOT IN ( 
   SELECT reservations.room_id 
     FROM reservations 
    WHERE (     reservations.arrivaldate   >=  $arrival_datetime 
            AND reservations.departuredate <=  $departure_datetime
          ) 
       OR (     reservations.arrivaldate   <=  $arrival_datetime 
            AND reservations.departuredate >=  $arrival_datetime 
          ) 
       OR (     reservations.arrivaldate   <=  $departure_datetime 
            AND reservations.departuredate >=  $departure_datetime 
          )
 );

如何从上面的查询返回的每个room_id为另一个表(room_prices_table)中的选定时段(从$ arrival_datetime到$ departure_datetime)添加平均房价列。所以我需要查看名称与room_id相同的列...

room_prices_table:
date
room0001
room0002
room0003
...

这样的东西
SELECT AVG(room0003) 
  FROM room_prices_table 
 WHERE datum IS BETWEEN $arrival_datetime 
                    AND $departure_datetime 

...

1 个答案:

答案 0 :(得分:1)

这样的事情:

SELECT 
     r.room_id,
     COALESCE(AVG(rpt.room0003), 0) AS AVERAGE_RATE
FROM rooms r
     LEFT OUTER JOIN room_prices_table rpt
     ON r.room_id = rpt.room_id 
 AND 
     rpt.datum BETWEEN $arrival_datetime AND $departure_datetime
WHERE 
     r.room_id NOT IN (
     SELECT reservations.room_id 
       FROM reservations 
      WHERE (reservations.arrivaldate >=  $arrival_datetime AND 
             reservations.departuredate <=  $departure_datetime) OR 
            (reservations.arrivaldate <=  $arrival_datetime AND
             reservations.departuredate >=  $arrival_datetime) OR
            (reservations.arrivaldate <=  $departure_datetime AND 
             reservations.departuredate >=  $departure_datetime)
     )
GROUP BY
    r.room_id;

使用COALESCE function确保我们在room_prices_table中没有信息的房间得到0而不是NULL。