在MySQL Interval查询中返回0或NULL

时间:2013-11-28 03:15:35

标签: mysql

我正在尝试返回过去7天的行数数据集,目前我的结果看起来像这样;

Array
(
    [0] => Array
        (
            [count(*)] => 1
        )

    [1] => Array
        (
            [count(*)] => 2
        )

)

但是我要求结果为0的日期,即显示0,所以我有7个结果。

到目前为止,这是我的查询;

"SELECT count(*) 
   FROM tbl_users 
  WHERE date_sub(curdate(), INTERVAL 7 DAY) <= created 
     AND NOW() >= created 
  GROUP BY date(created)"

唯一的另一种选择是将“count(*)作为日期”,日期是计数的实际日期。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

正如我在评论中所说的那样:你应该有一个包含所有日期的表,并且在你的时间间隔内连接并使用SUM而不是COUNT。计数仅为表中存在的结果带来结果。假设您的间隔来自2013-01-01 to 2013-01-10并且您拥有theese registries:

Created
2013-01-01, 
2013-01-01, 
2013-01-02, 
2013-01-03

它将导致:2, 1, 1

sql无法知道应该存在01-04, 01-05, 01-06... 01-10

因此,您必须创建日期数据并与表格保持联接。像这样:

一些数据示例:

create table tbl_users(
    created date
);

insert into tbl_users values
    ( '2013-11-24' ), 
    ( '2013-11-24' ),
    ( '2013-11-25' ),
    ( '2013-11-25' ),
    ( '2013-11-25' ),
    ( '2013-11-26' ),
    ( '2013-11-27' ),
    ( '2013-11-27' ),
    ( '2013-11-27' ),
    ( '2013-11-28' ),
    ( '2013-11-29' );


create table alldays (
    dateday date
);

--this is just an example to fit the result for today: 2013-11-28
--this table should have all days for the year
insert into alldays values
     ( '2013-11-23' ),
     ( '2013-11-24' ),
     ( '2013-11-25' ),
     ( '2013-11-26' ),
     ( '2013-11-27' ),
     ( '2013-11-28' ),
     ( '2013-11-29' ),
     ( '2013-11-30' ),
     ( '2013-12-01' ),
     ( '2013-12-02' ),
     ( '2013-12-03' );

您的查询应该是:

 SELECT a.dateday, sum( if(b.created is null, 0, 1) ) 
   FROM alldays a left join tbl_users b on (a.dateday=b.created)
  WHERE a.dateday >= date_sub(curdate(), INTERVAL 7 DAY)  
    AND a.dateday <= NOW()
  GROUP BY a.dateday

请在此处查看:http://sqlfiddle.com/#!2/cee122/7

答案 1 :(得分:0)

您可以使用MySql CASE语句,如下所示:

http://dev.mysql.com/doc/refman/5.1/en/case.html

前:

   CASE YOUR QUERY
   WHEN IS NULL THEN 0
   [ELSE statement_list]
  END CASE