2013-03-11 143 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');