仅在第一个选择为空时选择

时间:2013-08-09 16:29:15

标签: sql select conditional

我真的没有得到这个,尝试使用coalesce()但没有结果......

我有一个选择(非常简化以理解问题):

select col1, 
       col2 
from   table1 t1 
where  table1.col1='value' 
       and table1.col2='value2' 
       and table1.col3='value3'

我真的需要一个结果,所以如果这个选择结果集为空(并且仅当它是 null)(没有结果)那么下面的sql select来到图片

select col1, 
       col2 
from   table1 t1 
where  table1.col1='another_value' 
       and table1.col2='another_value2'

我怎样才能将这两个选中? (任何推荐的语法都值得赞赏......)

4 个答案:

答案 0 :(得分:2)

类似的东西:

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

答案 1 :(得分:1)

如果您的示例中有更多信息,那么它可能会对我们有所帮助。两个表之间是否存在可以建立JOIN的共同值?

SELECT  col1 
        ,col2  
FROM    Table1 t1
WHERE  table1.col1='value' 
   and table1.col2='value2' 
   and table1.col3='value3'  
UNION 
SELECT  col1 
        ,col2
FROM    Table2 t2 
WHERE  table1.col1='another_value' 
   and table1.col2='another_value2'
WHERE   NOT EXISTS (SELECT 1 FROM Table1 t1 WHERE t1.Col1 = t2.Col2)

答案 2 :(得分:0)

您可以使用COALESCE,如下所示:

select COALESCE (
(select col1, 
       col2 
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')
)

答案 3 :(得分:0)

这是我丑陋的解决方案。

select top 1 with ties
       col1, 
       col2
from   table1 
where  (
          col1='value' 
          and col2='value2' 
          and col3='value3'
       ) OR
       (
          col1='another_value' 
          and col2='another_value2'
       )
order by 
          CASE
          WHEN col1='value' 
                 and col2='value2' 
                 and col3='value3'
            THEN 1
            WHEN col1='another_value' 
                 and col2='another_value2'
            THEN 2 END

<强> SQL Fiddle DEMO