查找可用日期

时间:2016-04-29 17:24:26

标签: mysql sql date

我有两张桌子(1.订单和2.车):

汽车

Cars

订单

Orders

我正在尝试查找在给定日期可用的所有汽车。在这种情况下,我想找到2016-05-03和2016-05-05之间的所有可用汽车。我检查了NOT BETWEEN所述日期的汽车或尚未在订单中登记的汽车(orders.car_id IS NULL)。这是查询:

SELECT destination, COUNT(destination) AS 'available cars' 
FROM cars
LEFT JOIN orders ON cars.id = orders.car_id

WHERE (orders.car_id IS NULL

OR (

  date_to NOT BETWEEN '2016-05-03' AND '2016-05-05' 
  AND date_from NOT BETWEEN '2016-05-03' AND '2016-05-05'

  )

) 

AND destination = 'Kristiansand' GROUP BY destination

问题在于奥迪A1,id = 8 。如您所见,它在两个约会中注册,一个从2016-05-032016-05-05,一个从2016-04-292016-04-30

由于4月底的第二对日期是NOT BETWEEN查询中的给定日期,因此A1是可用的汽车,远非真实。

  

我正在尝试取出所有可用于租赁的汽车   克里斯蒂安桑的约会。

4 个答案:

答案 0 :(得分:1)

从排他性中改变你的想法:

  date_to NOT BETWEEN '2016-05-03' AND '2016-05-05' 
  AND date_from NOT BETWEEN '2016-05-03' AND '2016-05-05'

到包含:

  (date_from < '2016-05-03' AND date_to < '2016-05-05') OR
  (date_from > '2016-05-03' AND date_to > '2016-05-05')

答案 1 :(得分:1)

我认为更容易找到哪些车辆不可用,然后将其从列表中排除。像这样:

SELECT destination, COUNT(destination) AS 'available cars'
FROM cars
LEFT JOIN orders ON cars.id = orders.car_id 
        AND (date_to BETWEEN '2016-05-03' AND '2016-05-05' 
        OR date_from BETWEEN '2016-05-03' AND '2016-05-05')

WHERE orders.car_id IS NULL
    AND destination = 'Kristiansand' GROUP BY destination

答案 2 :(得分:1)

假设您有2个T1和T2期,以检查它们是否重叠 你做这个检查(T1.start&lt; = T2.end)AND(T1.end&gt; = T2.start)。

所以请尝试以下查询,(检查并确保不存在与指定期间重叠的同一辆车的订单

SET @startdate = '2016-05-03',@enddate = '2016-05-05';

SELECT c.destination,COUNT(c.destination) as available_cars
FROM cars c
WHERE NOT EXISTS (SELECT 1 
                  FROM orders o
                  WHERE o.car_id = c.id
                  AND o.date_from <= @enddate
                  AND o.date_to >= @startdate)
AND c.destination = 'Kristiansand'
GROUP BY c.destination

http://sqlfiddle.com/#!9/9340e3/4

您可以删除@enddate和@startdate

中的SET语句和硬编码

答案 3 :(得分:1)

这是正确的,因为你有理论上你在结果集中有2个不同的AUDI 。我可以建议使用HTTP Error 405: Method Not Allowed代替BETWEEN,获取已订购的汽车,并使用带有子查询的语句NOT BETWEEN将其从汽车表中排除,例如下面的示例。

NOT IN

注意:此查询未经过测试,如果您提供SQLFiddle或类似内容,我们可以执行此操作。

P.S。使用SELECT destination, COUNT(destination) AS 'available cars' FROM cars WHERE cars.id NOT IN ( SELECT DISTINCT car_id FROM orders WHERE date_to BETWEEN '2016-05-03' AND '2016-05-05' AND date_from BETWEEN '2016-05-03' AND '2016-05-05' ) 语句可以使用NOT EXISTS和子查询来实现相同的更佳方法。