打印本文 打印本文 关闭窗口 关闭窗口
先排序还是先取值
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2011  更新时间:2009/4/22 23:21:40  文章录入:mintao  责任编辑:mintao

                                                          先排序还是先取值

 

题目:  MS SQLSERVERORACLE中取出表中按照某字段排序的前N条记录

 

这个题目看上去似乎那么简单, 两种数据库都提供ORDER BY 子句. 问题应该能够迎刃而解吧.

 

先试一下MS SQLSERVER是怎么做的:

     

use Northwind;

create table TestSort (ID integer);

insert into testSort values (3);

insert into testSort values (1);

insert into testSort values (4);

insert into testSort values (2);

select * from testSort;    

-----------------------------------------

ID         

-----------

3

1

4

2

(4 row(s) affected)

 

假设我们要取出按照ID排序的前三条记录:

    

select TOP 3 * from testSort order by ID ;       

-----------------------------------------

ID         

-----------

1

2

3

(3 row(s) affected) 

 

很简单,一句话就解决了.

 

再试一下ORACLE (这里用ORACLE9i)

SQL>  create table TestSort ( ID number);

Table created.

SQL> insert into testSort values (3);

1 row created.

SQL> insert into testSort values (1);

1 row created.

SQL> insert into testSort values (4);

1 row created.

SQL> insert into testSort values (2);

1 row created.

SQL> commit;

Commit complete.

SQL> select * from testSort;

ID

----------

         3

         1

         4

         2

 

ORACLE没有MS SQLSERVER中取前N条记录的TOP语法. 但是有ROWNUM可以用来完成类似功能.

 

SQL> select * from TestSort where rownum <= 3 order by ID;

ID

----------

         1

         3

         4

 

结果是不是有点出乎意料? 它并没有返回所要求的 1 , 2 , 3的结果 . ORACLE先根据rownum <=3的条件限制选取一个范围集合(3,1,4), 然后再在这个集合里进行排序.

ORDER BY 子句是在合适的记录被取出后才起作用.

原来如此, 那么在ORACLE中如何才能实现这个功能呢?

通常我们可以采用这种办法:

SQL> select * from (select * from TestSort order by ID) where rownum <=3;

        ID

[1] [2]  下一页

打印本文 打印本文 关闭窗口 关闭窗口