mysql使用内部联接获取用户排名

时间:2014-11-25 07:56:05

标签: mysql

我有三张表如下。我想获得最高级别的用户。

1)用户表为

id        | user_id  | created_at
1         | 100      |   2014-11-07 02:54:09
2         | 102      |   2014-11-08 03:52:40
3         | 103      |   2014-11-10 02:47:26
4         | 104      |   2014-11-11 02:54:48
5         | 105      |   2014-11-14 03:11:23
6         | 105      |   2014-11-15 00:56:34

2)user_profile表为

id        | user_id  | rank
1         | 100      |   100
2         | 102      |   500
3         | 103      |   10
4         | 104      |   0
5         | 105      |   11
6         | 105      |   1000

3)user_followers表为

id        | user_id  | followers
1         | 100      |   10
2         | 102      |   20
3         | 103      |   30
4         | 104      |   40
5         | 105      |   0
6         | 105      |   50

现在我的查询是我想获得table2中排名最高的用户列表。如果领带用户与表3中的最高粉丝将获胜。如果是相同的关注者,首先创建的用户将获胜。

另一个我想找到用户ID传递相同逻辑的用户等级。

我已经尝试了类似

的内容
SET @i=0;
SELECT user_id, rank, @i:=@i+1 AS rank FROM user_profile ORDER BY rank DESC

2 个答案:

答案 0 :(得分:0)

SET @rank = 0;
SELECT
 @rank := @rank + 1 AS rank, *
FROM
(
SELECT users.user_id, user_profile.rank, user_followers.followers, users.created_at
FROM users
LEFT JOIN user_profile ON users.user_id = user_profile.user_id
LEFT JOIN user_followers ON users.user_id = user_followers.user_id
ORDER BY user_profile.rank DESC, user_followers.followers DESC, users.created_at ASC
)

答案 1 :(得分:0)

Arion的答案看起来像这样......

SELECT
users.*
FROM
users
JOIN user_profile
    ON users.user_id = user_profile.user_id
JOIN user_followers
    ON user_profile.user_id=user_followers.user_id
ORDER BY
user_profile.rank DESC,
user_followers.followers DESC,
users.created_at DESC

......但这似乎更接近你所追求的......

 SELECT u.user_id
      , u.created_at
      , up.rank
      , uf.followers 
      , @i:=@i+1 corrected_rank
   FROM users u 
   LEFT 
   JOIN user_profile up 
     ON up.user_id = u.user_id 
   LEFT 
   JOIN user_followers uf 
     ON uf.user_id = u.user_id
  CROSS
   JOIN (SELECT @i:=1) v
  ORDER
     BY rank DESC
      , followers DESC
      , created_at ASC;