SQL一请求加入表group_concat
Posted
技术标签:
【中文标题】SQL一请求加入表group_concat【英文标题】:SQL one request joining table group_concat 【发布时间】:2013-12-08 01:55:04 【问题描述】:我有这三个非常简单的表:
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 加载一个用户,只用一个请求并得到这样的结果:
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'
]
我该如何解决这个问题?
感谢您的帮助!
【问题讨论】:
【参考方案1】:两个 LEFT JOIN 将结果相乘,为用户 1 提供 6 个结果(3 辆汽车 x 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
【讨论】:
以上是关于SQL一请求加入表group_concat的主要内容,如果未能解决你的问题,请参考以下文章