尝试合并 SQL 查询的两个结果

我正在尝试使用 PHP 在 MYSQL 中合并两个查询的两个结果,但我很困惑如何去做!我正在使用 PDO。我正在为一种爱好编程,并正在尝试制作一个待办事项列表应用程序,就像 Trello 板一样。但是,我只是不知道如何合并来自数据库中不同表的两个结果。


思路如下:


我有一个名为“task_lists”的表格,内容如下:


'list_id => 1, list_name = 'listOne'

'list_id => 2, list_name = 'listTwo'

还有一个名为“任务”的表:


task_id => 1, list_id => 1, task_name => 'taskOfListOne', duration => 5, is_done => 1

task_id => 2, list_id => 1, task_name => 'anotherTaskOfListOne', duration => 5, is_done => 1

task_id => 3, list_id => 2, task_name => 'taskOfListTwo', duration => 10, is_done => 0


我正在尝试创建一个在两个结果之间合并的数组,如下所示:(我知道这是数组应该是什么样子的粗略图片)


$result = [array]

[list_id] = 1, [list_name] = 'listOne' => 

                     [array][list_id] = 1, ['task_name] = taskOfListOne,[duration] = 5, ['is_done'] => 1

                     [array][list_id] = 1, ['task_name] = anotherTaskOfListOne,[duration] = 5, ['is_done'] => 1

[list_id] = 2, [list_name] = 'listTwo' =>

                     [array][list_id] = 2, ['task_name] = taskOfListTwo,[duration] = 5, ['is_done'] => 1



这甚至可能吗?我已经尝试过 Union sql 查询和嵌套 foreach 语句之类的方法,但它们都不适合我。我在这里错过了什么吗?


PS:对不起我的英语不好。


慕丝7291255
浏览 121回答 1
1回答

精慕HU

你试过左连接吗?SELECT TL.`list_id`, TL.`list_name`, T.`task_name`, T.`duration`&nbsp;&nbsp;FROM task_lists AS TLLEFT JOIN tasks as T ON TL.`list_id` = T.`list_id`然后在 PHP 中,您以所需的格式构建数组。稍后编辑: 根据您的要求解析 SQL 数据的简单 PHP 示例(删除重复信息):<?php// $mysql_rows -> here is your query result, fetched as associative array$filtered_array = array();foreach ($mysql_rows as $row){&nbsp; &nbsp; // Initiate record if is not already initiated&nbsp; &nbsp; if (!isset($filtered_array[ $row['list_id'] ])){&nbsp; &nbsp; &nbsp; &nbsp; $filtered_array[ $row['list_id'] ] = array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'list_id'&nbsp; &nbsp;=> $row['list_id'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'list_name' => $row['list_name'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'tasks'&nbsp; &nbsp; &nbsp;=> array()&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp; // Add tasks&nbsp; &nbsp; $filtered_array[ $row['list_id'] ]['tasks'][] = array(&nbsp; &nbsp; &nbsp; &nbsp; 'task_name'&nbsp; => $row['task_name'],&nbsp; &nbsp; &nbsp; &nbsp; 'duration'&nbsp; &nbsp;=> $row['duration'],&nbsp; &nbsp; &nbsp; &nbsp; 'is_done '&nbsp; &nbsp;=> $row['is_done ']&nbsp; &nbsp; );}// Optional: if you want to remove list_id from $filtered_array key names, uncomment the next line// $filtered_array = array_values($filtered_array);?>
打开App,查看更多内容
随时随地看视频慕课网APP