1

我有简单的 SQL 查询:

SELECT * FROM t1 
WHERE status = 1 AND user_id = ? AND some_field NOT IN (?, ?, ..., ?)
ORDER BY createdAt DESC, rating DESC
LIMIT 10 OFFSET 0;

但是我想在我的 PHP 代码中对没有循环的用户集合执行类似的查询。看起来我需要在 user_id = 中使用 IN 子句?条件 (user_id IN (?,...?)) 并为 user_id IN 子句中的每个 id 单独的 LIMIT,OFFSET 子句。我知道这是不可能的,但可能存在任何变通方法而不会降低我的查询性能?

我使用 PostgreSQL 9.0.3 并且我假设也可以使用存储过程来解决这个问题。

4

1 回答 1

2
select *
from (
    select *,
        row_number() over(
            partition by user_id
            order by createdat desc, rating desc
        ) as rn
    from t1 
    where
        status = 1 and some_field not in (?, ?, ..., ?)
        and user_id in (1,2,3)
) s
where rn <= 10
order by user_id, rn

窗口功能:

http://www.postgresql.org/docs/current/static/functions-window.html

http://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS

http://www.postgresql.org/docs/current/static/tutorial-window.html

于 2013-08-19T12:29:04.527 回答