我想做的事情是:
根据提供的签入和结帐日期获取房间可用性计数。
以下是表格:
categories
id | name
1 | Luxe
2 | Deluxe
reservations
id | category_id | checkin | checkout
1 | 1 | 2018-01-06 | 2018-01-10
1 | 2 | 2018-01-11 | 2018-01-13
3 | 2 | 2018-01-13 | 2018-01-17
预期输出
由于category_id = 2
可以从2018-01-06
一直到2018-01-10
(请参阅reservations
表格中的第一行),我正在尝试包含其可用性计数,取总数。
所以在运行此查询时
SELECT
categories.name AS category,
COUNT(reservations.id) AS free_count
FROM reservations
INNER JOIN categories ON categories.id = reservations.category_id
WHERE checkin BETWEEN '2018-01-06' AND '2018-01-10'
GROUP BY categories.name, reservations.id
输出结果为:
category | free_count
Luxe | 1
但是我愿意输出:
category | free_count
Luxe | 1
Deluxe | 0
即将非匹配行替换为零。怎么做到这一点?非常鼓励没有嵌套查询的解决方案(由于性能低下)。
答案 0 :(得分:1)
使用LEFT JOIN
代替INNER JOIN
SELECT
c.name AS category,
COUNT(r.id) AS free_count
FROM categories c
LEFT JOIN reservations r
ON c.id = r.category_id
AND checkin BETWEEN '2018-01-06' AND '2018-01-10'
GROUP BY c.name
将checkin
过滤器保持在ON
条件非常重要。当您在Where
子句中保留正确的表格过滤器时,不匹配的记录将具有NULL
值,由于where
条件(基本上Left join
将在转换为Inner join
)