SQL 具有双重不同日期迭代的查询,并且开始日期 < 我的日期 < 最终日期

SQL Query with double distinct dates iteration, and start date < my date < final date

我有一种租赁系统数据库,用户可以在其中租用整栋房子,或者只是房子的一个房间。

我有一个名为 offers 的 table,其中包含 idroom_id 和更多列。

如果room_id = NULL,则指的是整个房子。

我有一个名为 availability 的 table,其中包含 offer_idroom_iddatestatus 列(可用、不可用)

如果room_id = NULL,则表示整栋房子有空房

select `offer_id` , `room_id`
from `availability` 
where `date` > CAST('2016-05-17' as date) 
  and `date` <= CAST('2016-05-21' as date) 
  and `status` = 'available' 
group by `offer_id` 
having COUNT(DISTINCT `date`) = DATEDIFF('2016-05-21', '2016-05-17')

好的,但我的问题是:如果一个房间在第 20 天不可用,但房子在第 20 天有另一个房间可用,则查询将 return 错误且模糊 select。我需要 room_id 为空(整个房子)的所有可用性,以及 room_id 不为空且在比较每个 offer_id 的日期时不同的分离结果(offer_id= 1 和 room_id = 1,offer_id = 1 和 room_id = 2 ...)

示例数据:

http://sqlfiddle.com/#!9/f5dfe

CREATE TABLE `availability` (
`offer_id` int(10) UNSIGNED NOT NULL,
`room_id` int(10) UNSIGNED DEFAULT NULL,
`date` date NOT NULL,
`status` enum('available','UNAVAILABLE') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'available'
);

INSERT INTO `availability` (`offer_id`, `room_id`, `date`, `status`) VALUES
(1, NULL, '2016-05-18', 'UNAVAILABLE'),
(1, NULL, '2016-05-19', 'available'),
(1, NULL, '2016-05-20', 'available'),
(1, NULL, '2016-05-21', 'available'),
(1, 1, '2016-05-18', 'available'),
(1, 1, '2016-05-19', 'UNAVAILABLE'),
(1, 1, '2016-05-20', 'available'),
(1, 1, '2016-05-21', 'available'),
(1, 2, '2016-05-18', 'available'),
(1, 2, '2016-05-19', 'UNAVAILABLE'),
(1, 2, '2016-05-20', 'available'),
(1, 2, '2016-05-21', 'available'),
(1, 3, '2016-05-18', 'available'),
(1, 3, '2016-05-19', 'available'),
(1, 3, '2016-05-20', 'UNAVAILABLE'),
(1, 3, '2016-05-21', 'available');

使用上面的查询会给我一个结果(offer_id = 1),但正确的是没有结果。 因为 none 整个房子(room_id = null)或一个房间在搜索开始日期和结束日期之间所有日期都可用的日期时可用

更新为初始答案不正确: 以下fiddle有更多数据:http://sqlfiddle.com/#!9/d6602/1/0

SELECT `Offer_id`, `room_id`
from
    ( select `offer_id`, `room_id`
    from `availability` 
    where `date` > CAST('2016-05-17' as date) 
      and `date` <= CAST('2016-05-21' as date) 
      and `status` = 'available'
    group by `offer_id`, `room_id`
    having COUNT(DISTINCT `date`) = DATEDIFF('2016-05-21', '2016-05-17')) As HousesAndRooms
WHERE NOT `room_id` IS NULL OR (`room_id` is null AND`offer_id` NOT IN(
    ( select `offer_id`
    from `availability` 
    where `date` > CAST('2016-05-17' as date) 
      and `date` <= CAST('2016-05-21' as date) 
      and `status` = 'UNAVAILABLE'
      and not `room_id` is null
    group by `offer_id`, `room_id`
    having COUNT(DISTINCT `date`) > 0 ) 
  ) )

上面的查询选择日期范围内的所有可用报价(房屋和房间),其中 room_id 为空(即整栋房子),它将检查是否有任何不可用的房间(不是 room_id 为空)对于给定的日期范围。