SQL Left Join - 多次相同的结果
我有以下表格:
users
id
|名称
信息
ID |信息 | user_id
(表info中的user_id是外键=>连接到表users中的id)
用户可能有很多条目在信息表中(许多行中有相同的 user_id)。
现在我想获取数据并像这样显示它:
username:
... info ....
示例:
admin:
aaa
bbb
ccc
someuser:
ddd
eee
fff
所以我像这样使用 LEFT JOIN:
SELECT users.name, info.info
FROM users
LEFT JOIN info
ON users.id = info.user_id
但我得到的是以下内容:
admin:
aaa
admin:
bbb
admin:
ccc
如何仅显示用户名一次?我尝试在 SELECT
之后使用 DISTINCT
关键字,但没有帮助。同时我在php代码本身内部解决了这个问题,但是有没有办法只在sql内部解决这个问题?
I have the following tables:
users
id
| name
info
id | info | user_id
(user_id from table info is foreign key => connects to id from table users)
It is possible that the user will have many entries in the info table (same user_id in many rows).
Now I want to fetch data and display it like that:
username:
... info ....
Example:
admin:
aaa
bbb
ccc
someuser:
ddd
eee
fff
So I use LEFT JOIN like that:
SELECT users.name, info.info
FROM users
LEFT JOIN info
ON users.id = info.user_id
But what I get is the following:
admin:
aaa
admin:
bbb
admin:
ccc
How can i display the username only once? I've tried using DISTINCT
keyword after SELECT
but it didn't help. Meanwhile i solve this problem inside the php code itself, but is there any way to fix this only inside the sql?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,
group_concat
使用,
作为分隔符,但您可以根据需要更改它。链接:
http://dev.mysql.com /doc/refman/5.5/en/group-by-functions.html#function_group-concat
By default
group_concat
uses a,
as separator, but you can change that if needed.Link:
http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat