Question

I have simple SQL query:

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

But I want to perform similar query for collection of users without cycle in my PHP code. Looks like I need to use IN clause in user_id = ? condition (user_id IN (?,...?)) and separate LIMIT,OFFSET clauses for each id in user_id IN clause. I know that is not possible, but maybe exists any workarounds without drop a performance of my query?

I use PostgreSQL 9.0.3 and I assume possibility of using stored procedure for solving this problem too.

Was it helpful?

Solution

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

Window functions:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top