标题: 请教个sql语句 ,谢谢 [打印本页] 作者: gengxl 时间: 2006-09-22 09:56 标题: 请教个sql语句 ,谢谢 我想查询最新的500条数据,用
select a.recid
from aaa a, bbb b
where a.recid = b.docid
and b.propc = 'xxx'
and rownum<500
order by a.lrsj desc
结果查询到最老的500条。
而用
select * from (select a.recid
from aaa a, bbb b
where a.recid = b.docid
and b.propc = 'xxx'
order by a.lrsj desc)
and rownum<500
就可以取得最新的500条,这个是为什么呢,不用子查询,能实现目标吗?作者: blue_stone 时间: 2006-09-22 23:14
第一个语句会先求rownum < 500再排序
第二个语句会先排序, 在求rownum< 500作者: numenhuang 时间: 2006-09-23 01:57
原帖由 gengxl 于 2006-9-22 09:56 发表
我想查询最新的500条数据,用
select a.recid
from aaa a, bbb b
where a.recid = b.docid
and b.propc = 'xxx'
and rownum<500
order by a.lrsj desc
...
这个就是要使用oracle TOP-N sql的写法
实际上第一个查询之所以得不到想要的结果,原因就在rownum这个变量的赋值。oracle在执行这条语句时,在分析完sql以后,一旦a.recid = b.docid and b.propc = 'xxx' 条件满足,此时oracle就会先将rownum赋值一次,而order by这个clause会在sql搜索整个完毕以后才会执行,所以不会得到想要的结果集。