MySQL query: multiple select with different conditions and LIMIT for each, but also LIMIT whole query + paginator friendly
0
votes
0
answers
379
views
I would like to write SQL query (for MySQL) that is able to SELECT
- x rows by condition1 from table1
- y rows by condition2 from table1+join1
- z rows by condition3 from table1+join2
But on every page (LIMIT+OFFSET), it must be full of "n" rows (so only on the last page there can be different number of rows than "n").
There can be different number of rows for condition1,condition2 and condition3. If there wouldn't be enough rows for condition1, select more rows by condition2 or condition3. If there isn't enough rows for condition2, select more rows by condition1 (or condition3 if cond1 not possible). And if there isn't enough rows for cond1+cond2, more in condition 3.
Important is:
- each page (except the last one) has the same number of rows
- each condition returns "x","y" and "z" records if enough rows left
- records from table1 has to be globally unique by id (each ID from table1 just once in whole solution)
- effective, there is lots of records and operations (WHERE, ORDER BY, ...)
- preferred to return as single query
**Practical usecase:**
Query will be used in searching. Client will enter "word" to search, but we don't know, if the word is code of a product, some parameter or name of a product.
Goal is to return results for each category (code,parameter,name).
For example on each page there will be 10 products. We have to return 2 products found by code, 3 products found by parameter and 5 products found by name.
If there isn't any result for searching by code, return 5 products by parameter and 5 by name. Etc. In any case, still 10 records per page.
We have to distinguish, if product was found by code,parameter or name.
**Example**:
Without paginator:
condition1 returns ID from table1: 1 2 3
condition2 returns ID from table1: 11 12 13 14 15 16 17 18 19
condition3 returns ID from table1: 101 102 103 104 105 106 107 108 109 110
111 112 113 114 115 116 117 118 119 120 118 117 116
Every page contains 10 rows:
- 2 rows by condition1 from table1
- 3 rows by condition2 from table1+join1
- 5 rows by condition2 from table1+join2
Results I need on "page 1":
condition1 returns: 1 2
condition2 returns: 11 12 13
condition3 returns: 101 102 103 104 105
Results I need on "page 2":
condition1 returns: 3
condition2 returns: 14 15 16 17
condition3 returns: 106 107 108 109 110
Results I need on "page 3":
condition1 returns: nothing
condition2 returns: 18 19
condition3 returns: 111 112 113 114 115 116 117 118
Results I need on "page 4":
condition1 returns: nothing
condition2 returns: nothing
condition3 returns: 119 120
It there will be some crazy SQL query or if it wouldn't be possible, we can use stored procedure. But the performance is important.
Thank you a lot.
Asked by Nick
(1 rep)
Oct 9, 2022, 10:28 PM
Last activity: Oct 10, 2022, 09:18 AM
Last activity: Oct 10, 2022, 09:18 AM