加入其他表,日期范围为0

时间:2010-11-11 23:31:50

标签: sql mysql

我有两个关联表(简化架构)

mysql> describe booking;
+----------------+------------+
| Field          | Type       |
+----------------+------------+
| id             | int(11)    |
| room_id        | int(11)    |
| date_from      | date       |
| date_to        | date       |
+----------------+------------+   

mysql> describe room;       
+-------------+------------+
| Field       | Type       |
+-------------+------------+
| id          | int(11)    |
| isDouble    | tinyint(1) |
+-------------+------------+

我需要做的是获得在指定时间段(date_from,date_to)内没有预订的所有double(isDouble = true)房间。我想在一个查询中得到结果。

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

尝试:

Select Distinct id RoomId
From room r
Where isDouble = 1
 And Not Exists
   (Select * From booking
    Where room_id = r.id
      And date_from <= @EndDateRange
      And date_to >= @StartDateRange)

答案 1 :(得分:1)

SELECT *
  FROM room r
 WHERE r.isDouble
   AND NOT EXISTS (SELECT NULL
                     FROM booking b
                    WHERE (date_from BETWEEN 'date1' AND 'date2'
                       OR date_to BETWEEN 'date1' AND 'date2')
                      AND b.room_id = r.id)

答案 2 :(得分:0)

试试这个:SELECT * FROM room WHERE isDouble = 1 AND id NOT IN (SELECT room_id FROM booking WHERE date_to BETWEEN 'date1' AND 'date2')