如何使用GROUP_CONCAT显示用户名?

时间:2016-08-25 08:05:38

标签: mysql

我试图弄清楚如何在用户GROUP_CONCAT的mysql查询中显示用户名而不是userid。以下查询有效,但显示用户ID。如何显示用户名?

查询

SELECT p.user_name, p.user_id, up.file, GROUP_CONCAT(c.userid)
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
GROUP BY up.file

结果

user_name | user_id  |    file     |   GROUP_CONCAT(c.userid)

Peter         5         pic_1.jpg               2,5
Mary          6         pic_2.jpg               6
julian        2         pic_3.jpg              (null)

2 个答案:

答案 0 :(得分:1)

再次加入users表,并从那里获取用户名:

SELECT p.user_name, p.user_id, up.file, GROUP_CONCAT(cp.user_name)
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
LEFT JOIN tbl_users cp ON cp.user_id = c.userid
GROUP BY up.file

答案 1 :(得分:1)

据推测,onEndOfSpeech()有用户名。如果是,请将其用于tbl_users

GROUP_CONCAT()

注意我从SELECT up.file, GROUP_CONCAT(p.username) FROM tbl_uploads up LEFT JOIN tbl_users p ON up.user_id = p.user_id LEFT JOIN tbl_collab c ON up.file = c.file GROUP BY up.file; 删除了p.username。通常,在聚合查询中,所有列/表达式应该在SELECT或聚合函数的参数中。