gpt4 book ai didi

mysql 使用内连接获取用户排名

转载 作者:行者123 更新时间:2023-11-29 23:23:29 25 4
gpt4 key购买 nike

我有以下三个表。我想获得排名最高的用户。

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

现在我的查询是我想获取表2中最高排名的用户列表。如果出现平局,表 3 中拥有最高关注者的用户将获胜。如果关注者相同,先创建的用户将获胜。

另一个我想通过用户 ID 来查找具有相同逻辑的用户排名。

我已经尝试过类似的方法

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

最佳答案

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;

关于mysql 使用内连接获取用户排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27121356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com