Db2 从范围中选择

发布于 2024-11-16 17:21:20 字数 858 浏览 3 评论 0原文

我被要求在工作中修复一个 php 函数。原型是:

function select($cols, $table, $cond, $order, $start, $max);

用odbc_exec()查询数据库,用odbc_num_rows()返回行数。函数代码是这样的:

$this->query = "SELECT $cols FROM $table ";
if($cond) $this->query .= "WHERE $cond";
if($order) $this->query .= " ORDER BY ".$order;

这个函数用在很多地方,所以我不能从头开始写。它从许多表中获取记录。直到昨天,它还没有使用 $max 变量,因此它正在从数据库中读取所有记录。他们正在使用 iSeries Access ODBC 驱动程序。我查看了此处寻求答案但找不到。

我想使用 $start 变量,从 $start 开始读取并读取 $max 行。如果 $start 是 100 且 $max 50,我想获取 100-150 之间的记录。我昨天添加了这部分:

if($max) $this->query .= " FETCH FIRST " . $max . " ROWS ONLY ";

我找不到任何对我的问题有用的东西。我知道我可以使用 id 或类似的东西对一张表执行此操作。但我正在寻找一个通用的解决方案。

I am asked to fix a php function in my work. The prototype is:

function select($cols, $table, $cond, $order, $start, $max);

It queries the database with odbc_exec() and returns the number of rows with odbc_num_rows(). Function code is like this:

$this->query = "SELECT $cols FROM $table ";
if($cond) $this->query .= "WHERE $cond";
if($order) $this->query .= " ORDER BY ".$order;

This function is used in many places so i can't write it from scratch. It gets records from many tables. Until yesterday it was not using $max variable so it was reading all the records from the database. They are using iSeries Access ODBC Driver. I looked at here for answer but couldn't found.

I want to use the $start variable, to start reading from $start and read $max rows. If $start is 100 and $max 50, i want to get the records between 100-150. I added this part yesterday:

if($max) $this->query .= " FETCH FIRST " . $max . " ROWS ONLY ";

I couldn't found anything useful for my problem. I know i can do it for one table using id or something like that. But i am looking for a general solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巴黎盛开的樱花 2024-11-23 17:21:20

我解决了这个问题。

首先,您需要使用 php 将 $cols 中的每个列名称转换为 $table.columnName。

$this->query .= " ( SELECT ROW_NUMBER() OVER() AS rownum, $convertedColumns
                       FROM $table ) AS tmp WHERE rownum > ". $start ." " ;
if($max) {
    $last = $start + $max;
    $this->query .= " AND rownum <= ". $last . " ";
}

结果查询如下所示:

SELECT $cols FROM 
    ( SELECT ROW_NUMBER() OVER() AS rownum, $convertedCols ) AS tmp
WHERE rownum > $start AND rownum <= $max

I solved the problem.

First, you need the convert each column name in $cols to $table.columnName with php.

$this->query .= " ( SELECT ROW_NUMBER() OVER() AS rownum, $convertedColumns
                       FROM $table ) AS tmp WHERE rownum > ". $start ." " ;
if($max) {
    $last = $start + $max;
    $this->query .= " AND rownum <= ". $last . " ";
}

And as result query looks like this:

SELECT $cols FROM 
    ( SELECT ROW_NUMBER() OVER() AS rownum, $convertedCols ) AS tmp
WHERE rownum > $start AND rownum <= $max
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文