我有2个表,奖励和awards_user,并且在mysql查询上有LEFT JOIN的问题没有得到像我想要的结果
奖励:awardid | name | link
1 | award1 | photo link
2 | award2 | photo link
3 | award3 | photo link
4 | award4 | photo link
awards_user:
awardid | username
2 | mark
2 | jon
3 | mark
1 | jon
我试着得到这样的结果:
award name | award photo | Users
award1 | link | jon
award2 | link | mark,jon
award3 | link | mark
award4 | link | -------
这是我的尝试:
SELECT au.username
, au.userid
, a.link
, a.name
, a.awardid
FROM awards a
LEFT
JOIN awards_user au
ON au.awardid = a.awardid
WHERE a.forumid = 22
GROUP
BY a.awardid
, au.username
ORDER
BY a.awardid DESC
解决问题:
$all_awards = $db->query_read(" SELECT awards.name as name, awards.link as link,
GROUP_CONCAT(DISTINCT awards_user.username) AS username
FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
where awards.forumid = '".$_REQUEST['forumid']."'
GROUP BY awards.awardid, awards.name, awards.link
");
答案 0 :(得分:0)
GROUP_CONCAT
完全符合您的要求:
SELECT
a.name AS name
, a.link AS photo
, GROUP_CONCAT(DISTINCT au.username) AS users
FROM awards AS a
LEFT JOIN awards_user AS au ON (au.awardid = a.awardid)
GROUP BY
a.awardid
, a.name
, a.link
ORDER BY
a.awardid DESC
此处有关MySQL GROUP_CONCAT
的更多信息:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
顺便说一下,你甚至可以在group_concat中对用户名进行排序或选择不同的分隔符。只需阅读MySQL手册和 google " mysql group_concat示例" :)
答案 1 :(得分:0)
并在表名上添加``,因为你的命名约定非常粗略可能与mysql保留字匹配,并再次实践安全过滤你的输入 $_REQUEST['forumid']
答案 2 :(得分:0)
试试这个:
SELECT awards.name as award_name, award.link as award_photo,
GROUP_CONCAT(DISTINCT awards_user.username AS users
FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
GROUP BY awards.awardid, awards.name, awards.link;