1

3 tables

table: people 

id name 
1  john  
2  Mike
3  Sam  
4  Andy 

-

table goods:

   g_id g_name  g_class
    1   sugar  food
    2   salt   food
    3   boat   transp
    4   house  habitation
    5   car    transp

-

   table goods_owned:
      go_id person_id   good_id
        1   3           3
        2   3           1
        3   3           5
        4   2           4
        5   1           2

Now when i select

SELCT people.id, people.name, goods.name
   FROM people
      LEFT JOIN goods_owned ON goods_owned.person_id = people.id
      LEFT JOIN goods ON goods.g_id = goods_owned.good_id
         WHERE people.id = 3

Then in response it duplicates entry's from table "people":

1, Mike, boat
1, Mike, sugar
1, Mike, car

Is there way to build request to get:

1, Mike, boat, sugar, car
4

1 に答える 1

4

はい、を見てくださいGROUP_CONCAT。これは、それぞれのすべての値を収集し、GROUP BYそれらをコンマで区切ります。

SELCT people.id, people.name, GROUP_CONCAT(goods.name)
FROM people
LEFT JOIN goods_owned ON goods_owned.person_id = people.id
LEFT JOIN goods ON goods.g_id = goods_owned.good_id
WHERE people.id = 3
GROUP BY people.id
于 2012-05-17T01:03:34.390 に答える