I'm using the following SQL to fetch posts
for each user by the user_id.
(select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 10)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 20)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 30)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 40)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 10)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 10)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
union all (select * from `posts` where `posts`.`user_id` in (?) limit 10 offset 0)
The limit ? offset ?
parts are used for the pagination for each user's posts.
For example limit 10 offset 20
means get "10 posts per page and page 3" for the specific user.
My Question is do I have better solution for this instead of union all
to improve the querying performance? Obviously this SQL have too many sub queries…
plus, here is the context and requirements for my use case.
- One query get both the user and the user's posts.
- Each user can have multiple posts.
- Each of the
?
is a differentuser_id
. - The
limit ? offset ?
can vary, but most of the time, the same value for each user.