MySQL选择连接表作为结果数组

时间:2017-05-31 19:17:18

标签: php mysql

我需要编写一个mysql查询,它将从Task表中选择父数据,在子SubTask表上执行左连接,并将子数据附加到Task数组下的数组中,如此...

任务

 id| details        | created
 ===============================
 1 | This is....    | 2017-08-19
 2 | This is....    | 2017-08-20
 3 | This is....    | 2017-08-21

子任务

 id  | task_id | details        | created
 ============================================
 123 | 1       | This is....    | 2017-08-19
 234 | 1       | This is....    | 2017-08-20
 345 | 2       | This is....    | 2017-08-21
 456 | 2       | This is....    | 2017-08-21
 567 | 3       | This is....    | 2017-08-21


 [
        [
            'id'=>1,
            'details'=>'This is from the task table',
            'subTasks'=>[
                [
                    'id'=>123,
                    'details'=>'This is from the sub task table',
                ],
                [
                    'id'=>234,
                    'details'=>'This is from the sub task table',
                ]
            ]
        ], 
        [
            'id'=>2,
            'details'=>'This is from the task table',
            'subTasks'=>[
                [
                    'id'=>345,
                    'details'=>'This is from the sub task table',
                ],
                [
                    'id'=>456,
                    'details'=>'This is from the sub task table',
                ]
            ]
        ]
        [
            'id'=>3,
            'details'=>'This is from the task table',
            'subTasks'=>[
                [
                    'id'=>567,
                    'details'=>'This is from the sub task table',
                ]
            ]
        ]
    ]

这是我的问题:

 $sql = "    SELECT    t.*,
                       (select st.* from SubTask) as SubTasks
             FROM      Task t
             LEFT JOIN SubTask st
                 ON       st.task_id = t.id
             ";

我知道这个查询不对,我只是不确定如何写它。

1 个答案:

答案 0 :(得分:2)

您不需要select子查询,只需:

SELECT t.id AS task_id, t.details AS task_details, st.id AS subtask_id, st.details AS subtask_details
FROM Task t
LEFT JOIN SubTask st ON st.task_id = t.id

然后您的PHP代码可以将所有子任务信息收集到一个数组中。

$tasks = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $task_id = $row['task_id'];
    if (!isset($tasks[$task_id])) {
        $tasks[$task_id] = ['id' => $task_id, 'details' => $row['task_details'], 'subtasks' => []];
    }
    if ($row['subtask_id'] !== null) {
        $tasks[$task_id]['subtasks'][] = ['id' => $row['subtask_id'], 'details' => $row['subtask_details']];
    }
}