MySQL连接在一个表上

时间:2013-09-16 10:37:44

标签: mysql sql join

我有一个像(短)的用户表:

id (BIGINT)
username (VARCHAR)
recommendedByUserId (BIGINT)

recommendedByUserId中存储推荐人的ID,即推荐人的users.id - 值。

现在我需要知道每个users.idusers.recommendedByUserId中的次数,并对它们进行降序排序,因此具有最多推荐的用户位于结果之上。

我试过了:

SELECT u.username, COUNT(r.id) FROM users u INNER JOIN users r ON u.id = r.recommendedByUserId

但这不起作用。

2 个答案:

答案 0 :(得分:3)

如果id足够

SELECT recommendedByUserId, COUNT(*) as rec_cnt
FROM users u 
group by recommendedByUserId
order by rec_cnt desc

如果您还需要该名称,则可以

select u.username, x.rec_cnt 
from users u
inner join
(
    SELECT recommendedByUserId as id, COUNT(*) as rec_cnt 
    FROM users u 
    group by recommendedByUserId
) x on x.id = u.id
order by x.rec_cnt desc

答案 1 :(得分:1)

SELECT recommendedByUserId, COUNT(*) as cnt
FROM users us 
group by recommendedByUserId order by cnt desc;