考虑这个表
id - name - age
1 jonny 12
2 al 16
3 lory 22
现在订购年龄我们有Lory,Al,Jonny。
有没有快速的方法来选择jonny在列表中的号码?
考虑到这个顺序SELECT * FROM table ORDER BY age DESC
,jonny是第3个。
类似于:SELECT *, * rank(age) as position** FROM table WHERE id = 1
编辑:
我可以统计年龄> gt的记录我的记录:所以查询变为:
SELECT COUNT(id) FROM table WHERE age > (SELECT age FROM table WHERE id = 1) as t1
我接受了答案,但我不喜欢在SQL查询中使用vars。
答案 0 :(得分:1)
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'
答案 1 :(得分:1)
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;