SQL 如果 select 语句不返回任何行,则执行替代的 select 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6466309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:06:25  来源:igfitidea点击:

SQL if select statement returns no rows then perform alternative select statement

sql

提问by YsoL8

Basically, what syntex would allow me to achieve the title statement?

基本上,什么语法可以让我实现标题声明?

If (select statement 1) returns 0 rows THEN (select statement 2) else (select statement 3)

So that the sql returns results from either statement 2 or 3 I've looked for a way to do this but nothing I've found so far seems to exactly address the if requirements.

为了使 sql 返回语句 2 或 3 的结果,我已经寻找了一种方法来执行此操作,但到目前为止我发现的任何内容似乎都无法完全满足 if 要求。

回答by ChrisBint

IF EXISTS (SELECT field FROM table)
BEGIN
SELECT field FROM table2
END
ELSE
BEGIN
SELECT field FROM table3
END

回答by Gans

Here you go...

干得好...

IF ((select count(*) from table1)= 0)
BEGIN
Select * from table2
END
ELSE
BEGIN
SELECT * from table3
END

回答by YsoL8

Sorry for the lack of feedback. Someone else in the office took an interest and came up with this:

很抱歉缺乏反馈。办公室里的其他人对此很感兴趣,并提出了以下建议:

select * from (
        select *
              , (SELECT Count(*) 
                   FROM users 
                  WHERE version_replace = 59 AND moderated = 1) AS Counter 
          FROM users WHERE version_replace = 59 AND moderated in (0,1)
     ) AS y
where Counter = 0 and Moderated = 0
   or Counter > 0 and Moderated = 1
ORDER By ID DESC

Which does what I need.

哪个做我需要的。