Consider the following table:
create table user_tasks
(
id bigserial primary key,
type varchar(255) not null,
...
);
I need to select 20 rows per page, but equally spread by type. Say, there are 10 distinct types, so I'm gonna need 2 rows of each. Every type has a different subset of filters that can be applied to it.
Here is how I do it right now, pseudo code:
array types = [...];
Collection typesSql = new Collection();
foreach (type of types) {
typesSql.push('SELECT * FROM user_tasks WHERE type =: type AND ... LIMIT 10');
}
string sql = typesSql->implode(' UNION ALL ');
array result = DB::query(sql);
I select 10 rows of each type, because I don't know in advance if there are enough rows of this particular type in the database, then I reduce the overall number from 100 to 20 if needed.
The query is quite slow, probably because I union all the 10 different queries. Is it possible to do it in a more efficient way? For example, is it possible to write query that selects a new type only if there are less than < 20 rows selected from all the previous types?