【问题标题】:PostgreSQL: using row_number() in paged outputPostgreSQL:在分页输出中使用 row_number()
【发布时间】:2011-06-03 10:51:31
【问题描述】:

我有一个 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']));

但是得到 ERROR: window function call requires an OVER 子句

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

我可能误解了Window Functions 文档。

【问题讨论】:

  • 什么是“语法错误”?你尝试了什么语法?你必须使用 OVER 和 ORDER BY,向我们展示你做了什么。 OVER(按 m.money ASC 订购)
  • @nate c:这是PHP中的prepared statement,我认为SQL注入在这里不会有问题。

标签: php postgresql rank


【解决方案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']));

【讨论】:

  • 谢谢,我不知道订单
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2014-04-21
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    相关资源
    最近更新 更多