SELECT语句中的SELECT返回0计数

时间:2013-08-20 07:57:06

标签: mysql sql select group-by

我有这个日历,每天都有一个事件列表,我使用这个查询来计算特定日期的事件。在我的数据库中,我有start_timeend_time字段,其中用户具有特定的材料计划。我试图select当天发生的事件,但我的查询似乎有些不对劲。因为用户可以借用多种材料,所以它也将存储在具有相同start_timeend_time的数据库中。我想要的是使用相同的start_time计算用户的所有数据,我尝试了GROUP BY,但它似乎也无效。这是我的数据库:

    ----Table: schedule----
    id    |   materialID  | borrowerID   | date_reserve | start_time | end_time| 
    -----------------------------------------------------------------------------------
    9     |    7          |    bobi      | 2013-08-16   | 07:01:12  |  07:01:12|    
    10    |    10         |    bobi      | 2013-08-16   | 07:01:12  |  07:01:12|
    11    |    12         |    bobi      | 2013-08-16   | 07:01:12  |  07:01:12|
    12    |    7          |    sobi      | 2013-08-18   | 07:01:12  |  07:01:12|
   ------------------------------------------------------------------------------------

这是我的问题:

    $cal_data = array();
   for($i=1;$i<=31;$i++)
    {
    $date = "$year-$month-$i";
    $this->db->select('(SELECT COUNT(id) as count_s FROM schedule WHERE date_reserve='.$date.' GROUP BY start_time) as count', FALSE);
    $this->db->select('date_reserve,borrowerID,start_time,end_time');
    $this->db->from('schedule');    
    $this->db->where('date_reserve',"$year-$month-$i"); 
    $this->db->group_by('start_time');
    $query = $this->db->get();

        foreach ($query->result() as $row) {

            $cal_data[$i] = ($row->count > 0) ? $row->count.' ' .'event(s)' : '';
        }
}   

因此预期的输出将是:

    count   |   date_reserve    | borrowerID   | start_time  | end_time
    ---------------------------------------------------------------------------------------------------
        1      |     2013-08-16     |        bobi       |  07:01:12  | 07:01:12

在这里有一个很大的 BUT ,在那个查询中它会给你这个输出。 注意:I'm using CodeIgniter
我使用$this->output->enable_profiler(TRUE);并在我的服务器上尝试使用日期2013-08-16(因为它是多项选择)到MySQL并给我这个。

    count   |   date_reserve    | borrowerID   | start_time  | end_time
    ---------------------------------------------------------------------------------------------------
     NULL   |     2013-08-16     |        bobi       |  07:01:12  | 07:01:12

那么您认为解决方案是什么?

2 个答案:

答案 0 :(得分:1)

这是你要找的吗?

select
count(distinct concat(date_reserve, ' ', start_time)) as my_count,
date_reserve,borrowerID,start_time,end_time
from
schedule
where borrowerID = 'bobi'

答案 1 :(得分:1)

基于fancyPants。查询CI:

$this->db->select('count(distinct concat(date_reserve, " ", start_time)) as my_count)', FALSE);
$this->db->select('date_reserve,borrowerID,start_time,end_time');
相关问题