Home > Software design >  MYSQL - how to perform second select if the firstone has no results?
MYSQL - how to perform second select if the firstone has no results?

Time:11-12

How to get result in MYSQL:

If First Select has more than 0 rows return the result, else return result from the Second select (not same tables, only one column in both selects).

Something like SELECT IF ((EXISTS(SELECT Column1 FROM Table1)),(SELECT Column1 FROM Table1),(SELECT Column1 FROM Table2);

CodePudding user response:

You could use a union trick here:

WITH cte AS (
    SELECT Column1, 1 AS pos FROM Table1
    UNION ALL
    SELECT Column1, 2 FROM Table2
)

SELECT Column1
FROM cte
WHERE
    pos = 1 OR
    NOT EXISTS (SELECT 1 FROM cte WHERE pos = 1);
  • Related