mysql相同的值不同的排名,如何根据不同的值对MySQL结果进行排名?

   日期:2024-12-28    作者:xdlbtl 移动:http://3jjewl.riyuangf.com/mobile/quote/76990.html

I have 2 different tables in my database by the name of: rank, settings.

Here is how each table looks like with a few records in them:

Table #rank:

id points userid

-- ----- ------

1 500 1

2 300 2

3 900 3

4 1500 4

5 100 5

6 700 6

7 230 7

8 350 8

9 850 9

10 150 10

Table #settings:

userid active

------ ------

1 0

2 1

3 1

4 1

5 1

6 0

7 1

8 1

9 0

10 1

What I basically want to achieve is to select a specific row from #rank by ID, sort it by points and select 3 rows above the specific ID and 3 row below the specific ID but only for rows where the active column (from #settings) for the user equals 1.

For example:

I would like to select from #rank the ID of 8, and it should return me the following:

rank points userid

---- ----- ------

2 150 10

3 230 7

4 300 2

5 350 8

6 900 3

7 1500 4

I have created quite an extensive query for this, but the problem is, that it is ranking the columns before it decides that the user is active or not. However I need to rank the columns after it is decided that the user is active or not.

SELECT sub2.sort, sub2.points, sub2.userid

FROM

(

SELECT @sort1 := @sort1 + 1 AS sort, puu.points, puu.userid

FROM rank as puu,

(SELECT @sort1 := 0) s

LEFT JOIN

(

settings as p11

)

ON puu.userid = p11.userid,

WHERE p11.active = 1

ORDER BY puu.points DESC

) sub1

INNER JOIN

(

SELECT @sort2:=@sort2+1 AS sort, p2.points, p2.userid

FROM rank as p2,

(SELECT @sort2 := 0) s

LEFT JOIN

(

settings as p12

)

ON p2.userid = p12.userid,

WHERE p12.active = 1

ORDER BY points DESC

) sub2

ON sub1.userid = :userid

AND sub2.sort BETWEEN (sub1.sort - 5) AND (sub1.sort + 5)

Can you guys find any solution for my problem? If you can provide an SQLfiddle demo, that would be really awesome!

解决方案SELECT sort, points, user_id, active FROM (

SELECT @pos := @pos + 1 AS sort, id, points, r.user_id, s.active,

IF(user_id = :userid, @userpos := @pos, 0)

FROM rank r

JOIN settings s USING(user_id)

JOIN (SELECT @pos := 0, @userpos := 0) p

WHERE s.active = 1

ORDER BY points DESC

) list

WHERE sort BETWEEN @userpos - 3 AND @userpos + 3


特别提示:本信息由相关用户自行提供,真实性未证实,仅供参考。请谨慎采用,风险自负。


举报收藏 0评论 0
0相关评论
相关最新动态
推荐最新动态
点击排行
{
网站首页  |  关于我们  |  联系方式  |  使用协议  |  隐私政策  |  版权隐私  |  网站地图  |  排名推广  |  广告服务  |  积分换礼  |  网站留言  |  RSS订阅  |  违规举报  |  鄂ICP备2020018471号