我真的不明白这一点,尝试使用合并()但没有结果......
我有一个选择(非常简化以理解问题):
select col1,
col2
from table1 t1
where table1.col1='value'
and table1.col2='value2'
and table1.col3='value3'
而且我确实需要一个结果,因此如果此选择结果集为空(并且仅当它为空时)(无结果),则以下 sql 选择出现在图片中
select col1,
col2
from table1 t1
where table1.col1='another_value'
and table1.col2='another_value2'
我怎样才能把这两个变成一个大的选择? (任何推荐的语法都值得赞赏......)
最佳答案
类似于:
; WITH Base AS (
select col1,
col2
from table1 t1
where table1.col1='value'
and table1.col2='value2'
and table1.col3='value3'
)
, Base2 AS (
select col1,
col2
from table1 t1
where table1.col1='another_value'
and table1.col2='another_value2'
AND NOT EXISTS (SELECT 1 FROM Base) -- HERE!!!
)
SELECT * FROM Base
UNION
SELECT * FROM Base2
我们希望 SQL 优化器不会运行第一个查询两次:-)
它是一个 CTE(通用表表达式)...我使用它是为了可以重复使用第一个查询两次(一个在 EXISTS
中,另一个在 SELECT ... UNION
中)
通过使用临时表
select col1,
col2
INTO #temp1 -- HERE!!!
from table1 t1
where table1.col1='value'
and table1.col2='value2'
and table1.col3='value3'
select col1,
col2
from table1 t1
where table1.col1='another_value'
and table1.col2='another_value2'
AND NOT EXISTS (SELECT 1 FROM #temp1) -- HERE!!!
关于sql - 仅当第一个选择为空时才选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18151437/