我有一个mysql表如下:t_id project_id task_id start_date---------------------------------------1 29 1 2020-03-092 29 2 2020-02-093 1 3 2019-02-204 1 4 2019-12-095 1 5 2019-12-09我想显示上表中的数据,以便所有数据都task_id必须显示为特定项目的特定日期的逗号分隔值。假设project_id=1我start_date首先列出所有日期,然后我将显示相同的任务start_date将被列为逗号分隔。预期结果是:start_date task_id-----------------------2019-02-20 32019-12-09 4,5我尝试使用 2 个 foreach 循环来实现相同的效果,但没有得到预期的结果。下面是我的代码:控制器:$id = $this->uri->segment(4); $dates = $this->Timesheet_model->get_tasks_dates($id); //get the datesforeach($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 ).我知道这不是一个复杂的问题,但目前我无法找到实现这一目标的正确解决方案。有没有其他有效的方法来解决这个问题?
1 回答
弑天下
TA贡献1818条经验 获得超8个赞
SELECT start_date,GROUP_CONCAT(task_id) as task_id
from project
where project_id = 1
group by start_date
您的问题可以使用这个单一查询来解决。
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消