简体   繁体   中英

SQL Query: Grouping results from two tables

Hello and thanks in advance. I have two tables:

users

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

tasks

|- 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  -|

I need some help to write a query for get an array grouping "tasks" by "user", something like the following one:

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
                        )
                )
        )
)

MySQL doesn't have "arrays". Perhaps using group_concat() will do what you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM