仅基于数据而不是日期和时间搜索MySQL数据库

时间:2014-04-16 03:25:31

标签: mysql sql date datetime

我有一个表,其中包含该行创建的日期时间信息。但是,我想在给定的时间范围内计算每天的创作数量。

select count(*), DateCreated FROM Stories WHERE DateCreated BETWEEN '2013-03-28' AND '2014-01-07' group by DateCreated;

然而,因为我按照DateCreated对它们进行了分组,所以尽管知道在同一天创建了多个故事,但我得到的数量为1。但是,datetime字段的时间部分使每个字段都足够独特,可以分组。

有没有办法可以修改我的查询以忽略日期时间的时间部分,并使用soley来区分组中的日期?

2 个答案:

答案 0 :(得分:2)

SELECT
    NumPerDay   = count(*), 
    DateCreated = cast(DateCreated as Date)
FROM 
    Stories 
WHERE 
    cast(DateCreated as Date) BETWEEN '2013-03-28' AND '2014-01-07' 
GROUP BY 
    cast(DateCreated as Date)

SELECT
    NumPerDay   = count(*), 
    DateCreated = DATE(DateCreated)
FROM 
    Stories 
WHERE 
    Date(DateCreated) BETWEEN '2013-03-28' AND '2014-01-07' 
GROUP BY 
    DATE(DateCreated)

或者,如果在where子句中强制使用Date Column来阻止使用可用索引:

SELECT
    NumPerDay   = count(*), 
    DateCreated = DATE(DateCreated)
FROM 
    Stories 
WHERE 
    DateCreated BETWEEN '2013-03-28 00:00:00' AND '2014-01-07 23:59:59.999' 
GROUP BY 
    DATE(DateCreated)

答案 1 :(得分:0)

只需将DateCreated投射到DATE,如下所示

SELECT
     count(*), DATE(DateCreated) 
FROM 
     Stories 
WHERE 
     DateCreated BETWEEN '2013-03-28' AND '2014-01-07' 
GROUP BY
    DATE(DateCreated);