我尝试进行选择,显示指定时间段(2016-04-22至2016-04-23)指定目的地的可用汽车总数。
在这种情况下,我想看看Mandal有多少可供出租的汽车。但是,在我的查询中,即使我已经指定了目的地,我也会给出Mandal中不可用的汽车总数。
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-04-22' AND '2016-04-23'
AND date_from NOT BETWEEN '2016-04-22' AND '2016-04-23'
AND destination = 'Mandal'
GROUP BY destination
运行上面的查询给出了下表: {{3}}
除了曼达尔的可用汽车外,它还只返回斯塔万格的一辆可用汽车,该汽车不应该显示也不正确。在斯塔万格,应该有两辆车可用(一辆在不同的时间租赁,NOT BETWEEN '2016-04-22' AND '2016-04-23'
,还有一辆尚未租赁,orders.car_id IS NULL
)。但Mandal的可用汽车数量是正确的。
答案 0 :(得分:1)
在构建复杂的WHERE
子句时,括号非常重要,因为它们可用于对当前使用的“范围”进行分组:
SELECT destination,
COUNT(sted) 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-04-22' AND '2016-04-23')
AND (date_from NOT BETWEEN '2016-04-22' AND '2016-04-23')
AND (destination = 'Mandal')
GROUP BY destination
您也可以考虑调整范围,只需使用小于/大于选项来更准确地定位范围(而不是BETWEEN
语句),它可能更容易阅读:
WHERE (date_from <= '2016-04-23' AND date_to >= '2016-04-22')
答案 1 :(得分:1)
我强烈怀疑where
条款需要on
条件:
SELECT destination, COUNT(sted) AS availablecars
FROM cars c LEFT JOIN
orders o
ON c.id = o.car_id AND
date_to BETWEEN '2016-04-22' AND '2016-04-23' AND
date_from BETWEEN '2016-04-22' AND '2016-04-23' AND
destination = 'Mandal'
WHERE o.car_id IS NULL
GROUP BY destination;
没有样本数据,我不是100%肯定。此外,日期条件可能是:
ON c.id = o.car_id AND
date_to >= '2016-04-22'
date_from <= '2016-04-23' AND
destination = 'Mandal'