mysql查询没有任何意义

时间:2013-03-11 08:24:14

标签: mysql

嘿伙计们,我有一张mysql表,其中包含一些记录,如下图所示!

date_time field has datetime datatype

我有以下查询来计算指定时间范围内的记录数(sr13,r4和huawei的记录数)。

$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。 查询有什么问题吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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');

答案 2 :(得分: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'");