问题:PostgreSQL:在分页输出中使用 row_number()

我有一个 PHP 脚本,显示按“虚拟货币”排序的玩家列表:

$sth = $db->prepare("
select u.id,
        u.first_name,
        u.city,
        u.avatar,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 20 offset ?
");
$sth->execute(array($_GET['offset']));

为了显示玩家在列表中的位置,我使用了一个 PHP 变量 $pos,该变量在循环中递增,同时打印他们的姓名和更多数据。

由于各种原因,我想在 SQL 语句中而不是 PHP 中拥有该位置。所以我正在尝试以下操作:

$sth = $db->prepare("
select u.id,
        row_number() + ? as pos,
        u.first_name,
        u.city,
        u.avatar,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 20 offset ?
");
$sth->execute(array($_GET['offset'], $_GET['offset']));

但是得到错误:窗口函数调用需要一个OVER子句

我正在尝试添加 over(m.money) 但出现语法错误。

我可能误解了窗口函数文档。

解答

检查用户注释:http://www.postgresql.org/docs/8.4/interactive/functions-window.html

您将需要 Over() 包含与整个查询相同的 order by 子句:

$sth = $db->prepare("
select u.id,
        row_number() OVER (order by m.money desc) + ? as pos,
        u.first_name,
        u.city,
        u.avatar,
        m.money,
        u.login > u.logout as online
from pref_users u, pref_money m where
        m.yw=to_char(current_timestamp, 'IYYY-IW') and
        u.id=m.id
order by m.money desc
limit 20 offset ?
");
$sth->execute(array($_GET['offset'], $_GET['offset']));
Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐