mysql count which record it is in ordered mode?
Consider this table
id - name - age
1 jonny 12
2 al 16
3 lory 22
Now ordering for age we have Lory, Al, Jonny.
Is there a fast way to select which number jonny is in the list ?
Considering this order SELECT * FROM table ORDER BY age DESC
, jonny is 3rd.
Something like: SELECT *, * rank(age) as position** FROM table WHERE id = 1
开发者_Go百科
EDIT:
I can count the records that have the age > my record: so the query become:
SELECT COUNT(id) FROM table WHERE age > (SELECT age FROM table WHERE id = 1) as t1
I have accepted an answer but i rly don't like to use vars in sql queries.
set @name = 'al';
select @name,count(*) + 1 as rank from
(select * from `table` where age >
(select age from `table` where name=@name) order by age desc)as tab;
SELECT
rownum
FROM
(
SELECT @rownum:=@rownum+1 rownum, id,age,name
FROM (SELECT @rownum:=0) table
ORDER by age desc
) temp
WHERE
temp.name = 'jonny'
精彩评论