This question already has an answer here:
MySql Count cannot show 0 values
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我想做的事情是:

根据提供的入住和退房日期获取房间可用性计数。

表格如下:

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 = 22018-01-062018-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


即将不匹配的行替换为零。如何做到这一点?强烈建议不要使用嵌套查询(由于性能低下)而提出的解决方案。

最佳答案

使用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

关于mysql - 将不匹配的行计数为零-如何? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48347647/

10-16 13:55