2013-11-23 39 views
1

我有這三個非常簡單的表格:SQL一個請求連接表GROUP_CONCAT

table user = 
[ 
    [ 
     'id'  => 1 
     'username' => 'user1' 
    ] 
    [ 
     'id'  => 2 
     'username' => 'user2' 
    ] 
    [ 
     'id'  => 3 
     'username' => 'user3' 
    ] 
] 

table cars = 
[ 
    [ 
     'id_user' => 1 
     'name'  => 'bmw' 
    ] 
    [ 
     'id_user' => 1 
     'name'  => 'audi' 
    ] 
    [ 
     'id_user' => 1 
     'name'  => 'honda' 
    ] 
    [ 
     'id_user' => 2 
     'name'  => 'dodge' 
    ] 
] 

table bikes = 
[ 
    [ 
     'id_user' => 1 
     'name'  => 'yamaha' 
    ] 
    [ 
     'id_user' => 1 
     'name'  => 'suzuki' 
    ] 
    [ 
     'id_user' => 3 
     'name'  => 'kawasaki' 
    ] 
] 

而且我想通過他的身份證,只有一個請求加載用戶得到的結果類似:

爲例與ID = 1:

array result = 
[ 
    'id'   => 1 
    'username' => 'user1' 
    'cars_name' => 'bmw##audi##honda' 
    'bikes_name' => 'yamaha##suzuki' 
] 

爲例使用id = 2:

array result = 
[ 
    'id'   => 2 
    'username' => 'user2' 
    'cars_name' => 'dodge' 
    'bikes_name' => '' 
] 

我曾嘗試這個請求:

' 
    SELECT 
     user.id, 
     user.username, 
     GROUP_CONCAT(cars.name SEPARATOR "##"), 
     GROUP_CONCAT(bikes.name SEPARATOR "##") 
    FROM 
     user 
    LEFT JOIN 
     cars ON user.id = cars.id_user 
    LEFT JOIN 
     bikes ON user.id = bikes.id_user 
    WHERE 
     user.id = $id 
    LIMIT 1 
' 

但這輸出(爲例與ID = 1):

array result = 
[ 
    'id'   => 1 
    'username' => 'user1' 
    'cars_name' => 'bmw##audi#honda##bmw##audi#honda' 
    'bikes_name' => 'yamaha##yamaha##yamaha##suzuki##suzuki##suzuki' 
] 

然而它正常工作與ID = 2和id = 3:

(ID = 2)

array result = 
[ 
    'id'   => 2 
    'username' => 'user2' 
    'cars_name' => 'dodge' 
    'bikes_name' => '' 
] 

(ID = 3)

array result = 
[ 
    'id'   => 1 
    'username' => 'user3' 
    'cars_name' => '' 
    'bikes_name' => 'kawasaki' 
] 

我該如何解決這個問題?

Thx任何幫助!

回答

0

兩個LEFT JOIN乘以你的結果,給你6個用戶1的結果(3輛車×2輛自行車)。

您可以在GROUP_CONCAT中使用DISTINCT來修復重複項。

docs

GROUP_CONCAT([DISTINCT ] EXPR [,... EXPR]

  [ORDER BY {unsigned_integer | col_name | expr} 
      [ASC | DESC] [,col_name ...]] 
     [SEPARATOR str_val]) 

它應該是這樣的:

SELECT 
    user.id, 
    user.username, 
    GROUP_CONCAT(DISTINCT cars.name SEPARATOR "##") AS cars, 
    GROUP_CONCAT(DISTINCT bikes.name SEPARATOR "##") AS bikes 
FROM user 
LEFT JOIN cars ON user.id = cars.id_user 
LEFT JOIN bikes ON user.id = bikes.id_user 
GROUP BY user.id 
+0

Thx bro它工作! – user3006522