开发者

SQL Left Join - same results multiple times

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 po开发者_如何转开发ssible 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?


SELECT users.name, GROUP_CONCAT(info.info SEPARATOR 'whateveryouwant') as info
FROM users 
INNER JOIN info ON (users.id = info.user_id)
GROUP BY users.name

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


$lastname="";
$res=mysql_query($yourQuery);
while($row=mysql_fetch_assoc($res)){
    if($row['name']!=$lastname){
        $lastname=$row['name'];
        print $lastname.':'; // first time print it
    }
    print $row['info'];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜