开发者

Pull one record out ordered by a field

开发者 https://www.devze.com 2023-02-16 23:13 出处:网络
I have a simple sql query that goes like this: SELECT * FROM leaderboard WHERE UserId = \'$sessfacebook\'\"

I have a simple sql query that goes like this:

SELECT * FROM leaderboard WHERE UserId = '$sessfacebook'"

This selects me a username, a facebookid and a num开发者_运维技巧eric score. I need to pull this record out but I need to find out which position the record is in if the table were ordered by the score. Hope this makes sense.


You can use another query for that

SELECT count(*) Position
FROM leaderboard
WHERE score >= (
    SELECT score
    FROM leaderboard
    WHERE UserId = '$sessfacebook')

Which you can slot in as a subquery

SELECT *, (
    SELECT count(*)
    FROM leaderboard b
    WHERE b.score >= leaderboard.score) Position
FROM leaderboard
WHERE UserId = '$sessfacebook'


You could use a subquery to select the number of records with a higher score:

SELECT  * 
,       (select count(*) from leaderboard lb2 where lb2.score > lb1.score) as Rank
FROM    leaderboard lb1
WHERE   UserId = '$sessfacebook'"


SELECT * from (SELECT @ranknum := @ranknum + 1 AS rank, 
leaderboard.* FROM leaderboard , (SELECT @ranknum := 0) r order by score desc) 
as sortedboard where USERID = '$sessfacebook' limit 1;

This will create a table alias as leaderboard with rank, and get the required record from it. Will work for you, tested it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号