Using MySQL, how do I select query result rank of one particular row?

☆樱花仙子☆ 提交于 2019-12-02 09:46:04

问题


I've spent quite a lot of time today trying various things, but none of them seem to work. Here's my situation, I'd like to be able to select the rank of a row based on it's ID from a specifically sorted row

For example, if my query is something like:

SELECT id, name FROM people ORDER BY name ASC

with results like:

id   name
3    Andrew
1    Bob
5    Joe
4    John
2    Steve

I would like to get the rank (what row it ends up in the results) without returning all the rows and looping throw them until I get to the one I want (in PHP).

For example, I'd like to select the 'rank' of 'Steve' so that it returns -- in this case -- 5 (not his id, but the 'rank' of his name in the above query).

Similarly, I'd like to be able to select the rank of whatever row has the ID of 1. For this example, I'd like to return a 'rank' of 2 (because that's in what result row there is an ID of 1) and nothing else.

I've Google'd as much as I could with varying results... either having really slow queries for larger tables or having to create all sorts of temporary tables and user variables (the former I'd REALLY like to avoid, the latter I suppose I can live with).

Any help or insight would be greatly appreciated.


回答1:


from artfulsoftware:

SELECT p1.id, p1.name, COUNT( p2.name ) AS Rank
    FROM people p1
    JOIN people p2 
    ON p1.name < p2.name
    OR (
         p1.name = p2.name
         AND p1.id = p2.id
    )
GROUP BY p1.id, p1.name
ORDER BY p1.name DESC , p1.id DESC
LIMIT 4,1



回答2:


Something like this?

SELECT Row, id, name
FROM (SELECT @row := @row + 1 AS Row, id, name
      FROM people
      ORDER BY name ASC)
WHERE Row = @SomeRowNumber

If you want to go by the ID, just alter the where clause.




回答3:


Try this:

SELECT @rownum:=@rownum+1 `rank`, p.id, p.name
FROM people p, (SELECT @rownum:=0) r
ORDER BY name ASC



回答4:


I try to this code... may help other I am getting result from users and upload table for user profile pic and join it than after i am calculating user points and sorting on them. At last am checking and adding row number for ranking for users... Injoy it. thanks

set @row_num = 0;
set @calp =0;
select  if(@calp=(@calp:=user.cal_points), @row_num, @row_num := @row_num + 1) as row_number,user.* from 
(select user_skills.*,users.username,upload.file_name from user_skills join users on user_skills.user_id=users.id join upload on upload.upload_id=users.profile_pic order by user_skills.cal_points desc) as user
WHERE user.skill_name LIKE  '%ph%'


来源:https://stackoverflow.com/questions/1262448/using-mysql-how-do-i-select-query-result-rank-of-one-particular-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!