【问题标题】:select records with dates in where condition and group the results based on each date选择日期在 where 条件下的记录并根据每个日期对结果进行分组
【发布时间】:2020-03-11 09:36:56
【问题描述】:

我有一个mysql表如下:

t_id    project_id  task_id  start_date
---------------------------------------
1        29         1       2020-03-09
2        29         2       2020-02-09
3        1          3       2019-02-20
4        1          4       2019-12-09
5        1          5       2019-12-09

我想显示上表中的数据,以便所有task_id 必须显示为特定项目的特定日期的逗号分隔值。假设project_id=1 我首先在start_date 中列出所有日期,然后我将显示具有相同start_date 的任务将以逗号分隔。

预期结果是:

start_date      task_id
-----------------------
2019-02-20      3
2019-12-09      4,5

我尝试使用 2 个 foreach 循环来实现相同的效果,但没有得到预期的结果。下面是我的代码:

控制器:

$id = $this->uri->segment(4);       
$dates = $this->Timesheet_model->get_tasks_dates($id); //get the dates
foreach($dates as $d)
    {
        $rows = $this->Timesheet_model->get_project_tasks_by_date($id,$d->start_date); //get tasks for each date
            foreach($rows->result() as $res)
            {
                $t[] = $res->task_id;
            }
        $ts = implode(",",$t);
        $tasks = array(
            'date'=>$d->start_date,
            'tasks'=>$ts
        );
    }
    print_r($tasks);

型号

public function get_tasks_dates($id)
{
    $sql = 'SELECT DISTINCT (start_date) FROM xin_tasks WHERE project_id = ? ORDER BY start_date DESC ';
    $binds = array($id);
    $query = $this->db->query($sql, $binds);

    return $query->result();
}

public function get_project_tasks_by_date($id,$d)
{
    $sql = 'SELECT task_id FROM xin_tasks WHERE project_id = ? AND start_date = ?';
    $binds = array($id,$d);
    $query = $this->db->query($sql, $binds);

    return $query;
}

当我尝试print_r($tasks) 时,结果是Array ( [date] => 2019-02-20 [tasks] => 4,5,3 )

我知道这不是一个复杂的问题,但目前我无法找到实现这一目标的正确解决方案。有没有其他有效的方法来解决这个问题?

【问题讨论】:

    标签: php mysql select foreach


    【解决方案1】:
    SELECT start_date,GROUP_CONCAT(task_id) as task_id
    from project
    where project_id = 1
    group by start_date
    

    您的问题可以使用这个单一的查询来解决。

    【讨论】:

      【解决方案2】:

      使用DISTINCT关键字,如果同一天重复相同的task_id

      SELECT start_date,GROUP_CONCAT(DISTINCT task_id) as task_id
      FROM project
      WHERE project_id = 1
      GROUP BY start_date;
      

      如果您使用DISTINCT,我们将获得唯一的task_id..

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多