我的查询有点像这样:
SELECT ISNULL(MyColumn, "Not Applicable") As MyColumn
FROM MyTable
WHERE SomeOtherColumn =
(SELECT AValue
FROM SomeOtherTable
WHERE SomeConditionHolds
)
如果MyColumn的相关值有一个值,我会得到它,如果它是null,这会让我“不适用”。
但是,偶尔子查询返回空集,在这种情况下整个查询也返回空集。我仍然希望它返回“不适用。”
我能做的最好的就是加入上面的
UNION
SELECT 'Not Applicable' AS MyColumn
WHERE NOT EXISTS
(SELECT AValue
FROM SomeOtherTable
WHERE SomeConditionHolds
)
但这感觉非常黑客和效率低下。我希望有人有更好的主意。
答案 0 :(得分: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
)
答案 1 :(得分:0)
试试这个:
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
答案 2 :(得分:0)
获取查询结果,当没有Row存在时,将结果设置为“Not Applicable”,否则必须仔细检查并浪费系统时间。
答案 3 :(得分:0)
由于您的子查询返回一个值,您可以轻松地将其转换为外部联接,这将始终为您提供一行,这也将使查询更加高效和优雅:
SELECT
ISNULL(MyColumn, "Not Applicable") As MyColumn
FROM MyTable
LEFT JOIN SomeOtherTable
ON SomeOtherColumn = AValue
AND SomeConditionHolds
这里的关键是SomeConditionHolds
在 join 条件中,不是 where子句,否则左连接有效地成为内连接。< / p>
答案 4 :(得分: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 )