开发者

Mysql -- Use a secondary subquery if and only if the first subquery returned empty

开发者 https://www.devze.com 2023-03-03 21:30 出处:网络
Given two subquery tables t1 and t2, how can I return t2 if and only if t1 returned empty开发者_如何学JAVA rows?

Given two subquery tables t1 and t2, how can I return t2 if and only if t1 returned empty开发者_如何学JAVA rows?

Edit: Added example

T1

SELECT * 
  FROM common_table 
 WHERE language_id = 1

T2

SELECT * 
  FROM common_table 
 WHERE language_id = 2

Basically what I am doing is that in case the T1 return empty rows, I would like it to execute T2 and return those rows. Now, I am fully aware that I can do this in PHP but the query is a subquery and I would rather let SQL (not PHP) code handle it.


Select ...
From common_table
Where language_id = 1
    Or  (
        language_id = 2
        And Not Exists  (
                        Select 1
                        From common_table
                        Where language_id = 1
                        )
        )


In MSSQL I can do something like

If EXISTS (SELECT * FROM common_table WHERE language_id = 1)
BEGIN
    SELECT * FROM common_table WHERE language_id = 1
END ELSE BEGIN
    SELECT * FROM common_table WHERE language_id = 2
END

Should be the same in mySQL or similar


My MySql knowledge is a bit rusty and I think this should work.

SELECT * FROM common_table 
         WHERE language_id = 2 and 
               0 = ( SELECT count(*) FROM common_table 
                                     WHERE language_id = 1
                   ) ;


SELECT * 
  FROM common_table 
 WHERE language_id = 1
UNION
SELECT * 
  FROM common_table 
 WHERE language_id = 2
       AND NOT EXISTS (
                       SELECT * 
                         FROM common_table AS T2 
                        WHERE T2.language_id = 1
                      );
0

精彩评论

暂无评论...
验证码 换一张
取 消