2013-03-11 94 views
0

嘿家伙我有一张mysql表,里面有一些记录,如下图所示!mysql查询不计数

date_time field has datetime datatype

我有以下查询来计算记录(记录为SR13,R4和华为号)在指定时间范围内的号码。

$date1 = "2012-01-02 03"; 
$date2 = "2014-12-30 24"; 
$counter_result = $this->db->query("select count(sr13) as count_sr13, count(r4) as count_r4, count(huawei) as count_huawei from cdrcount where date_time BETWEEN '$date1%' and '$date2%' "); 

查询将返回为0 三个字段的值是否有任何一点毛病的查询?

+0

你真的试图比较'date_time'对两个字符串到底通配符占位符''%? – 2013-03-11 08:26:28

+0

是的,这是我正在运行的查询! – goseo 2013-03-11 08:27:17

+0

查询可能会产生零行,这就是为什么它们都是“0”。 – 2013-03-11 08:27:21

回答

0

要正确比较日期,您应该使用这些全值:

$date1 = "2012-01-02 03:00:00"; 
$date2 = "2014-12-30 23:59:59"; 

而且从查询删除%

$counter_result = $this->db->query("select count(sr13) as count_sr13, count(r4) as count_r4, count(huawei) as count_huawei 
    from cdrcount 
    where date_time BETWEEN '$date1' and '$date2'"); 
0

原因是因为date_time被隐式转换为字符串,因为BETWEEN中的值包含%。因此,相比较于字符串数据类型日期与包含%,显然没有记录相匹配,尝试删除其值,

select count(sr13) as count_sr13, 
     count(r4) as count_r4, 
     count(huawei) as count_huawei 
from cdrcount 
where date_time BETWEEN '$date1' and '$date2' 

,你的时间应该被格式化成一个有效的日期例如,2012-01-02 03:00:00

0

尝试time_to_sec功能

select count(sr13) as count_sr13, count(r4) as 
count_r4, count(huawei) as count_huawei from cdrcount 
where time_to_sec(date_time) 
BETWEEN time_to_sec('date1') and time_to_sec('date2');