最近用到oracle库,明显和之前用的SQL有很多区别什么关键字 top 中这不能用,oracle什么又来个rownum 下面总结下在oracle中查询前N条的方法及心得
首先在SQL2005 中可以: select top 10* from table1; 在关联order by 等条件就可实现前N条的统计排序,oracle中按照这种方法显然执行不通过
先看以下简单的查询前N条语句(按照统计排序后显示前N条记录):已测通
--test pass
select id from (select id ,rownum as con from (select id from llt_org_info a order by id desc) where rownum<=10)where con>=1
然后按照以下结构套入sql (测试未通过)
-- 未通 (报错ORA_00907 缺少右括号)
select a.id,a.org_code, a.org_name,
(select rownum as con from
(select count(*) from llt_report b where b.send_org_id =a.id) as org_count from llt_org_info a order by org_count desc
where rownum<=10)
where con >1
由sql里到外分析:
第一层: select count(*) from llt_report b where b.send_org_id =a.id) as org_count from llt_org_info
由语句可看出根据关联关系表中统计数量 OK
第二层:(select count(*) from llt_report b where b.send_org_id =a.id) as org_count from llt_org_info a order by org_count desc
where rownum<=10) (测试未通过)
oracle中解析过程可得之rownum 为查询出来自带的伪数列,便于数据集的标识但必须在查询结果确定后也就是
第二层:(select count(*) from llt_report b where b.send_org_id =a.id) as org_count from llt_org_info a order by org_count desc )
where rownum<=10
放入语句中:
-- 未通 (报错ORA_00907 缺少右括号)
select a.id,a.org_code, a.org_name,
(select rownum as con from
(select count(*) from llt_report b where b.send_org_id =a.id) as org_count from llt_org_info a order by org_count desc )
where rownum<=10
where con >1
先来看下测试通过的SQL:
select id,org_code,org_name,org_count from
(SELECT ROWNUM RN ,A.* FROM
(select id,org_code,org_name,
(select count(*) from llt_report b where b.send_org_id=c.id) as org_count from Llt_org_Info c order by org_count desc)
A WHERE ROWNUM <=10) WHERE RN >0
再次分析语句:第一层统计没问题,第二层排序后没问题,但是第二层查询后得出数据集 oracle 对此数据集重新定义rownum 并且查询后的结果集为一张新表,在对这张新表另起别名来操作
所以第三层 :(SELECT ROWNUM RN ,A.* FROM (...........) A where rownum<=10
最后在根据相关显示列,最外层取查询字段
总结:oracle 中提供rownum 对伪数列编号,利用rownum 对其结果集的编号来排序 进而控制前N条数据的显示。