如何从Oracle中的表中选择带有顺序的远程行?

时间:2012-11-02 16:02:58

标签: sql oracle

在Oracle中没有限制,所以我使用了这个:

SELECT * 
FROM ( 
     SELECT m.*, ROWNUM r 
     FROM TABLE_NAME m  
     WHERE COL LIKE XYZ 
     ORDER BY ID ASC
     ) 
WHERE r BETWEEN 10 AND 20;

但它仍未订购。它从20个订购,但不是整个表。我怎样才能做到这一点?

我想用WHERE子句对整个表进行排序并获得远程表。上述解决方案仅在该范围内订购。


可能不那么混乱的解决方案(如果有人在这里搜索):

SELECT a.* from (
  SELECT b.*, ROWNUM r FROM ( 
    SELECT * FROM table ORDER BY id ASC  
  ) b  WHERE  (city LIKE '%abc%' OR city IS NULL)
) a where r between 5 and 10

因此,最好将顺序置于中间标准,然后将其他标准放在第二级,并将行号放在最外层。

1 个答案:

答案 0 :(得分:1)

据我所知,您需要更多级别的嵌套,例如:

select b.* from (
 select a.*, rownum rnum from (
  select * from foo order by id
 ) a where rownum <= 20
) b where b.rnum >= 10;

演示:

SQL> create table foo (id number);
Table created.
SQL> insert into foo
  2   select round(dbms_random.value(0, 1000))
  3   from dual
  4   connect by level <= 15;
15 rows created.
SQL> commit;
Commit complete.

rownum在订购之前得到“物化”,因此您的方法无法正常工作,正如您所注意到的那样:

SQL> select foo.*, rownum from foo order by id;

    ID     ROWNUM
---------- ----------
        24     15
       148      5
       151      2
       225      7
       234     11
       292      1
       305      4
       351      9
       383      8
       394     13
       426     12
       477     10
       553      6
       594     14
       917      3
15 rows selected.

所以嵌套一次以获得订购后的行号:

SQL> select a.*, rownum from (
  2   select * from foo order by id
  3  ) a;

    ID     ROWNUM
---------- ----------
        24      1
       148      2
       151      3
       225      4
       234      5
       292      6
       305      7
       351      8
       383      9
       394     10
       426     11
       477     12
       553     13
       594     14
       917     15
15 rows selected.

但你不能用between做这个:

SQL> select a.*, rownum from (
  2   select * from foo order by id
  3  ) a where rownum between 5 and 10;

no rows selected

这是因为rownum只在行进入结果集时获取一个值。 并添加第二层以删除第一行:

SQL> select id, rnum from (
  2   select id, rownum rnum from (
  3    select id from foo order by id
  4   ) a where rownum <= 10
  5  ) b where b.rnum >= 5;

    ID   RNUM
---------- ----------
       234      5
       292      6
       305      7
       351      8
       383      9
       394     10

6 rows selected.