开发者

mysql table join problem

开发者 https://www.devze.com 2023-03-08 02:55 出处:网络
table: user idname ------------- 1john 2开发者_Python百科paul 3mattew table: nickname iduser_idnickname

table: user

id     name
-------------
1      john
2      开发者_Python百科paul
3      mattew

table: nickname

id    user_id    nickname
--------------------------
1     1          frog
2     1          cow
3     1          bull
4     2          cat

Result I want:

 1     john     frog cow bull
 2     paul     cat
 3     mattew     

How can I get this result?


Something like this should work:

SELECT u.id, u.name, GROUP_CONCAT(n.nickname, ' ') AS nickname
FROM user u
LEFT JOIN nickname n ON u.id = n.user_id
GROUP BY u.id, u.name

Please Note: syntax for GROUP_CONCAT may not be perfect because I haven't used it in a while


Use mysql aggregate functions: Group concat will do the trick for you.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

0

精彩评论

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