如何在mysql的日期范围内将所有日期值显示为null?

时间:2016-02-15 05:46:11

标签: mysql

我有一张预订表,需要在MYSQL中查找特定日期范围内的预订次数。但它只给我非空值。我需要在我的选择查询中将范围内的非存在日期显示为NULL。这是我的疑问:

SELECT DATE_FORMAT(booking_created_on, '%b %e') AS dateValue , COUNT(booking_id) AS cnt FROM booking WHERE booking_created_on BETWEEN '2016/02/01' AND '2016/02/08' GROUP BY booking_created_on

此查询的结果是:

enter image description here

我的预期结果是:

enter image description here

请帮我解决mysql查询以获得所需的结果。

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT DATE_FORMAT(selected_date, '%b %e'), cnt 
FROM(
        SELECT 
        str_to_date(booking_created_on, '%Y/%m/%d') AS selected_date , 
        COUNT(booking_id) AS cnt 
        FROM booking 
        WHERE booking_created_on BETWEEN '2016/02/01' AND '2016/02/08' 
        GROUP BY booking_created_on

        UNION          

        SELECT selected_date,0 AS cnt FROM 
        (SELECT adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date FROM
         (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t0,
         (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1,
         (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2,
         (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t3,
         (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t4) v
        where selected_date BETWEEN '2016-02-01' and '2016-02-08' AND selected_date NOT IN (
                SELECT 
                DISTINCT(str_to_date(booking_created_on, '%Y/%m/%d')) FROM booking 
                WHERE booking_created_on BETWEEN '2016/02/01' AND '2016/02/08' 
        )
) AS T1 
ORDER BY selected_date ;

在我的查询中,首先我得到你的表中的所有日期和计数,并在第二个子查询中得到所有缺少的日期,这两个日期之间不在你的表中。按日期显示结果顺序。这是冗长的查询,所以可能会有一些错误,所以如果有任何错误,请注释