我正在尝试返回上传次数最多的前三位用户。然后,我计算了3个顶级用户中每个用户的上传次数。现在它只返回一个用户,并且计数会计算所有上传,即使上传不属于该用户。
这是我的表格设置:
上传:( id,userID,名称,位置,类型)
用户:(id,fname,lname,username,avatar,country,pw)
SELECT u.id, u.userID, COUNT(us.id) as top_nums, us.username, us.avatar, us.country
FROM upload u LEFT OUTER JOIN user us ON us.id=u.userID
ORDER BY top_nums DESC LIMIT 3
提前感谢您的帮助!!
答案 0 :(得分:1)
我认为此查询可以解决您的问题:
SELECT us.id, us.username, us.avatar, us.country, COUNT(u.id) top_nums
FROM `user` us
LEFT JOIN upload u ON us.id = u.userId
GROUP BY u.userID
ORDER BY top_nums DESC LIMIT 3;
答案 1 :(得分:0)
您的查询中缺少GROUP BY
子句,
SELECT u.id, u.userID, COUNT(us.id) as top_nums, us.username, us.avatar, us.country
FROM upload u
LEFT OUTER JOIN user us
ON us.id=u.userID
GROUP BY u.id, u.userID, us.username, us.avatar, us.country
ORDER BY top_nums DESC
LIMIT 3
但请记住,此查询不会处理关系。
答案 2 :(得分:0)
我想你想这样做:
select u.id, u.fname, u.lname, count(*)
from user u
left outer join upload up on u.id = up.userid
group by u.id, u.fname, u.lname
order by count(*) desc
答案 3 :(得分:0)
select us.username, us.avatar, us.country ,
(select count(*) from upload u where u.id=us.id) as no_of_uploads
from users us order by 4 desc limit 3;