我有简单的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子句? condition(user_id IN(?,...?))并为user_id IN子句中的每个id分别设置LIMIT,OFFSET子句。我知道这是不可能的,但可能存在任何变通方法而不会降低我的查询性能?
我使用PostgreSQL 9.0.3并且我也假设可以使用存储过程来解决这个问题。
答案 0 :(得分: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