1

If I do:

SELECT * FROM A   
WHERE conditions  
UNION  
SELECT * FROM B   
WHERE conditions 

I get the union of the resultset of query of A and resultset of query of B.

Is there a way/operator so that I can get a short-circuit OR result instead?

I.e. Get the result of SELECT * FROM A WHERE conditions and only if this returns nothing get the resultset of the SELECT * FROM B WHERE conditions ?

4

3 回答 3

5

简短的回答是否定的,但您可以避免第二个查询,但您必须重新运行第一个:

SELECT * FROM A   
WHERE conditions  
UNION  
SELECT * FROM B   
WHERE NOT EXISTS (
    SELECT * FROM A   
    WHERE conditions)
AND conditions

这假设优化器帮助并缩短第二个查询,因为 NOT EXISTS 的结果对于所有行都是错误的。

如果第一个查询比第二个查询便宜得多,那么如果第一行返回行,您可能会获得性能。

于 2013-09-03T22:41:14.833 回答
1

您可以使用单个 SQL 查询来执行此操作,如下所示:

SELECT *
FROM A   
WHERE conditions  
UNION ALL
SELECT *
FROM B   
WHERE conditions and not exists (select * from A where conditions);
于 2013-09-03T22:41:29.237 回答
0

您是否尝试过“如果”语句?

If(select Count(*) from A where conditions) > 0 
Then Select * from A where conditions
Else Select * from B where conditions
于 2013-09-03T22:39:53.793 回答