3

我有一个 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)但出现语法错误。

我可能误解了Window Functions文档。

4

2 回答 2

1

你想要row_number() OVER (ORDER BY m.money) + ?的等等。

于 2011-01-04T20:14:54.597 回答
1

检查用户注释: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']));
于 2011-01-05T07:04:12.593 回答