[英]How to join two tables on two columns normally, but if one of columns contain null, then result must contain rows that match another column only?
我有兩張桌子。 一個表是項目列表,第二個表示過濾器。 篩選器表上的列可以包含null。 它的聲明如下:
declare @item table(x int, y int);
declare @filter table(x int null, y int null);
insert into @item
values
(1, 1), (1, 5),
(2, 4), (2, 1), (2, 5),
(3, 5);
insert into @filter
values
(1, 1),
(1, null),
(2, 1),
(null, 5);
它們必須在x和y列上連接。 結果應僅包含Item表中的列,這些列在Filter表中具有相同鍵的列。 但是..如果Filter表中的任何鍵列的值為null,則結果應包括Items表中與第二個鍵列匹配的所有行。
我的意思是:
select item.*
from @item as item
left join @filter as filter
on (item.x = filter.x and item.y = filter.y)
/* Something must be here, or join must be written somehow else */
-- Current result:
----------
-- x y
----------
-- 1 1
-- 2 1
-- Should be:
-------------
-- x y
-------------
-- 1 1
-- 1 5
-- 2 1
-- 2 5
-- 3 5
如何以這種方式加入這個表?
你可以嘗試這樣....
select Distinct item.*
from @item as item
inner join @filter as filter
on (item.x = Coalesce(filter.x,item.x) and item.y = Coalesce(filter.y,item.y))
我認為你的意思是在你的join ON
子句中使用CASE
espression,如下所示
select item.*
from @item as item
left join @filter as filter
on item.x = CASE
WHEN filter.x IS NULL THEN filter.y ELSE filter.x
END
and item.y = CASE
WHEN filter.y IS NULL THEN filter.x ELSE filter.y
END
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.