我想知道当我使用SQL连接时如何避免重复值 例如:
Table: Users
[id] [name]
1 Bob
2 Junior
Table: images
[id] [img] [user_id]
1 water.jpg 1
2 spoon.jpg 2
3 beer.jpg 1
如何从数据库中获取这些值:
id => 1
name => Bob
img => [water.jpg, beer.jpg]
id => 2
name => Junior
img => [spoon.jpg]
而不是
id => 1
name => Bob
img => water.jpg
id => 1
name => Bob
img => beer.jpg
id => 2
name => Junior
img => spoon.jpg
我使用MySQL对此有什么疑问?
答案 0 :(得分:2)
您可以使用group by
和group_concat()
:
select u.id, u.name, group_concat(i.img) as imgs
from users u join
images i
on u.id = i.user_id
group by u.id;
答案 1 :(得分:1)
试试这个:
SELECT users.id, users.name, concat('[',GROUP_CONCAT(images.img SEPARATOR ','),']') as images_concat
FROM users
INNER JOIN images ON (users.id = images.user_id)
GROUP BY users.id;