Mysql - 当且仅当第一个子查询返回空时,才使用辅助子查询

时间:2011-05-10 03:06:37

标签: mysql sql

给定两个子查询表t1和t2,当且仅当t1返回空行时,如何返回t2?

修改:添加了示例

T1

SELECT * 
  FROM common_table 
 WHERE language_id = 1

T2

SELECT * 
  FROM common_table 
 WHERE language_id = 2

基本上我正在做的是,如果T1返回空行,我希望它执行T2并返回这些行。现在,我完全清楚我可以在PHP中执行此操作,但查询是一个子查询,我宁愿让SQL( 不是PHP )代码处理它。

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

在MSSQL中我可以做类似

的事情
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

在mySQL或类似的

中应该是相同的

答案 2 :(得分:1)

我的MySql知识有点生疏,我认为这应该有用。

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

答案 3 :(得分:0)

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
                      );