我有一個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我想顯示上表中的數(shù)據(jù),以便所有數(shù)據(jù)都task_id必須顯示為特定項目的特定日期的逗號分隔值。假設(shè)project_id=1我start_date首先列出所有日期,然后我將顯示相同的任務(wù)start_date將被列為逗號分隔。預(yù)期結(jié)果是:start_date task_id-----------------------2019-02-20 32019-12-09 4,5我嘗試使用 2 個 foreach 循環(huán)來實現(xiàn)相同的效果,但沒有得到預(yù)期的結(jié)果。下面是我的代碼:控制器:$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;}當(dāng)我嘗試print_r($tasks)結(jié)果是Array ( [date] => 2019-02-20 [tasks] => 4,5,3 ).我知道這不是一個復(fù)雜的問題,但目前我無法找到實現(xiàn)這一目標(biāo)的正確解決方案。有沒有其他有效的方法來解決這個問題?
1 回答

弒天下
TA貢獻1818條經(jīng)驗 獲得超8個贊
SELECT start_date,GROUP_CONCAT(task_id) as task_id
from project
where project_id = 1
group by start_date
您的問題可以使用這個單一查詢來解決。
- 1 回答
- 0 關(guān)注
- 104 瀏覽
添加回答
舉報
0/150
提交
取消