sjerez
sjerez

Reputation: 7

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

Upvotes: 0

Views: 46

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269643

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;

Upvotes: 1

Related Questions