[英]select records with dates in where condition and group the results based on each date
我有一个 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 )
。
我知道这不是一个复杂的问题,但目前我无法找出实现这一目标的正确解决方案。 有没有其他有效的方法来解决这个问题?
SELECT start_date,GROUP_CONCAT(task_id) as task_id
from project
where project_id = 1
group by start_date
您的问题可以使用这个单一查询来解决。
使用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(s)..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.