a表中每个人年龄不同,标准SQL查询出年龄第三高的记录(一条)
SELECT id,name,age FROM a a1
where exists
(select 1 from a a2 where a1.age<=a2.age having count(1)=3)
a1.age a2.age
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
首先a1表中所有记录都会逐个被作为条件放到子查询中,看是否有记录返回,如果有则a1表中的单条记录成立,否则被剔除。
当a1.age为8时,子查询返回的结果是8,9,10,其count正好是3,所以符合要求。
标准SQL查询出年龄第三到第五高的记录
SELECT id,name,age FROM a a1
where exists
(select 1 from a a2 where a1.age<=a2.age having count(1) between 3 and 5)