SQL查询:对两个表的结果进行分组

时间:2018-02-19 01:31:16

标签: php mysql sql left-join

您好,并提前致谢。我有两张桌子:

用户

|- ID -|- NAME   -|
|- 1  -|- Will   -|
|- 2  -|- Isabel -|
|- 3  -|- Robert -|
|- 4  -|- John   -|
|- 5  -|- David  -|
|- 6  -|- Eric   -|

任务

|- ID -|- USER -|- DESCRIPTION         -|
|- 1  -|- 1    -|- Clean floor         -|
|- 2  -|- 1    -|- Clean windows       -|
|- 3  -|- 2    -|- Repair an appliance -|
|- 4  -|- 3    -|- Buy spare parts     -|
|- 5  -|- 1    -|- Remove stains       -|
|- 6  -|- 2    -|- Pick up the lounge  -|

我需要一些帮助来编写查询以获取数组分组"任务"用户",如下所示:

Array
(
    [0] => Array
        (
            [user] => 1
            [tasks] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [description] => Clean floor
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [description] => Clean windows
                        )

                    [2] => Array
                        (
                            [id] => 5
                            [description] => Remove stains
                        )
                )
        )
    [1] => Array
        (
            [user] => 2
            [tasks] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [description] => Repair an appliance
                        )

                    [1] => Array
                        (
                            [id] => 6
                            [description] => Pick up the lounge
                        )
                )
        )
    [2] => Array
        (
            [user] => 3
            [tasks] => Array
                (
                    [0] => Array
                        (
                            [id] => 4
                            [description] => Buy spare parts
                        )
                )
        )
)

1 个答案:

答案 0 :(得分:1)

MySQL没有"数组"。也许使用group_concat()会做你想做的事情:

select t.user,
       group_concat(t.id, ':', t.description order by t.id) as tasks
from tasks t
group by t.user;