Home  >  Q&A  >  body text

How to execute second query when first query has no results - MYSQL

How to get results in MYSQL:

If the first selection has more than 0 rows, return the result, otherwise return the result of the second selection ( is not the same table , there is only one column in the two selections).

Something similar SELECT IF ((EXISTS(SELECT COLUMN 1 FROM TABLE 1)),(SELECT COLUMN 1 FROM TABLE 1),(SELECT COLUMN 1 FROM TABLE 2);

P粉998100648P粉998100648399 days ago1007

reply all(1)I'll reply

  • P粉342101652

    P粉3421016522023-09-17 12:14:43

    You can use the joint 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);
    

    reply
    0
  • Cancelreply