将不匹配的行计为零 - 如何?

时间:2018-01-19 18:44:25

标签: mysql sql

我想做的事情是:

根据提供的签入和结帐日期获取房间可用性计数。

以下是表格:

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

即将非匹配行替换为零。怎么做到这一点?非常鼓励没有嵌套查询的解决方案(由于性能低下)。

1 个答案:

答案 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