2

我有一个有点像这样的查询:

SELECT ISNULL(MyColumn, "Not Applicable") As MyColumn
FROM MyTable
WHERE SomeOtherColumn =
(SELECT AValue
FROM SomeOtherTable
WHERE SomeConditionHolds
)

如果 MyColumn 的相关值有一个值,我会得到这个值,如果它为空,这会根据需要给我“不适用”。

但是,有时子查询会返回空集,在这种情况下,整个查询也会返回空集。我仍然希望它返回“不适用”。

我能做的最好的就是添加到上面

UNION
SELECT 'Not Applicable' AS MyColumn
WHERE NOT EXISTS
    (SELECT AValue
FROM SomeOtherTable
WHERE SomeConditionHolds
)

但这感觉真的很笨拙且效率低下。我希望有人有更好的主意。

4

5 回答 5

1
SELECT ISNULL(MyColumn, DummyCol) As MyColumn
FROM MyTable 
  RIGHT OUTER JOIN (SELECT 'Not Available' AS DummyCol) Q ON DummyCol IS NOT NULL
   AND SomeOtherColumn =
     (SELECT AValue
     FROM SomeOtherTable
     WHERE SomeConditionHolds
     )
于 2013-05-11T04:27:55.513 回答
0

Try this :

    SELECT Case When T.AValue Is Null Then 'Not Applicable' Else MyColumn End As MyColumn
    FROM MyTable Left Outer Join 
   (SELECT AValue
    FROM SomeOtherTable
    WHERE SomeConditionHolds
   ) T on MyTable.SomeOtherColumn  = T.AValue
于 2013-05-10T19:22:12.013 回答
0

获取查询结果,当不存在行时设置结果为“不适用”,否则您必须仔细检查并浪费系统时间。

于 2013-05-10T19:28:30.447 回答
0
declare @Foo as Table ( FooId Int Identity, Something VarChar(16) );
insert into @Foo ( Something ) values
  ( 'One' ), ( 'II' ), ( '3' );

declare @FooLimit as Int = 1; -- Try 5.

with Alicia as (
  select FooId, Something, 1 as SetId
    from @Foo
    where FooId >= @FooLimit
  union all
  select 42, 'n/a', 2 )
  select FooId, Something
    from Alicia
    where SetId = ( select Min( SetId ) from Alicia )
于 2013-05-19T02:51:50.603 回答
0

由于您的子查询返回一个值,因此您可以轻松地将其转换为外部联接,这将始终为您提供一行,这也将使查询更加高效和优雅:

SELECT
    ISNULL(MyColumn, "Not Applicable") As MyColumn
FROM MyTable
LEFT JOIN SomeOtherTable
    ON SomeOtherColumn = AValue
    AND SomeConditionHolds

这里的关键SomeConditionHolds是在连接条件中,而不是在 where 子句中,否则左连接实际上变成了内连接。

于 2013-05-11T04:08:44.837 回答