Oracle db分页查询困难,错误是:“命令未正确结束”

时间:2014-02-04 05:34:06

标签: php oracle plsql oracle-sqldeveloper

我正在进行以下查询以进行分页。 我跑的时候

$s= oci_parse($conn,"select * from TBL_Name order by D_DATE desc");
$r = oci_execute($s);

然后没有显示错误。当我写下以下内容时:

$s= oci_parse($conn,"select * from TBL_Name order by D_DATE desc limit $start,$limit");
$r = oci_execute($s);

error is:  oci_execute(): ORA-00933: SQL command not properly ended .

这意味着问题在于" limit $start,$limit ",但我需要这个用于分页。 LIMIT在Oracle中无效。现在我该怎么写这个查询?

2 个答案:

答案 0 :(得分:1)

limit $start,$limit仅适用于MySQL,它对Oracle或其他数据库没有帮助(尽管@Charles在评论中指出,LIMIT with OFFSET is used elsewhere as well)。

使用Oracle,就像

select * from (
select foo.*, ROWNUM rnum
  from  
( select * from TBL_Name order by D_DATE desc  ) foo
 where ROWNUM <= $end) where rnum >= $start;

答案 1 :(得分:1)

ROWNUM是您的结果集生成的内容。 pseduocolumn ..所以它总是小于等于..所以我们首先使用不同的名称生成最大限制和别名的rownums ..并使用从外部查询引用的别名。

select * from 
( select a.*, ROWNUM rnum from 
  (select * from TBL_Name order by D_DATE desc ) a 
  where ROWNUM <= $end )
where rnum  >= $start;

PHP代码

// Parse a query containing a bind variable.
$stmt = oci_parse($conn, "    select * from  " +
                                          " ( select a.*, ROWNUM rnum from " +
                                          "   (select * from TBL_Name order by D_DATE desc ) a "+
                                          "    where ROWNUM <= :end) "+
                                          "   where rnum  >= :start) ");

// Bind the value into the parsed statement.
oci_bind_by_name($stmt, ":end", $end);
oci_bind_by_name($stmt, ":start", $start);