0

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

1
  • If you don't want to run the second query unless the first returns fewer than 10 rows, then do it in code as you show. Commented Oct 10, 2022 at 15:50

1 Answer 1

0

You can have a dummy column to count the rows from table_a and then can use a sub-query to have your desired result -

SELECT value
  FROM (SELECT 1 as src, value
          FROM table_a
         UNION
        SELECT 2 as src, value
          FROM table_b
        ORDER BY src
        LIMIT 10
       ) x;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer but that will not "short circuit" or stop the select 2... the part after union from being executed
Even if that step executed, You will only get the 10 records from table_a only. If it does not have 10 records, Then only it will include records from table_b.
I know and understand that but will still execute the query and wait until those 10 rows are calculated and fetched. I am curious to know if there is a way to not execute the second query if have already 10 rows from first query therefore not wait X ms/s for the second query
Since I am using LIMIT 10. So it will never executes 2nd query if you get 10 rows from table_a only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.