I am selecting some rows from different tables The logic is like this: I want to return in total only 10 results, I try first table_a and if I cannot fetch 10 rows from table_a I fill the remaining rows from the results fetched from table_b
Pseudo-query
select value from table_a limit 10
union # ONLY IF COULD NOT FETCH 10 values from table_a
(select value from table_b limit 10)
limit 10
Is something like this possible in mysql and if yes how ?
Some simple test cases
test case 1: that if I can fetch 10 rows form table_a don't want to execute the union as I have enough results.
test case 2: I got 4 values(rows) from table_a then union executes and I get N more rows from table_b, in total should never get more than 10 rows (limit 10)
test case 3: 0 items in table_a, the query will only return up to at most 10 items from table_b
PS: I am aware and know how to solve this via the programming language.
In that case would be as easy as:
$queryA = 'select value from table_a limit 10';
$results = $sql->execute($queryA);
if (count($results) < 10) {
$queryB = sprint('select value from table_b limit %d', 10 - count($results));
$resultsB = $sql->execute($queryB);
$results = $results + $resultsB;
}
I wonder if can be done in a more elegant minimal way directly from mysql