我有两张桌子。一个表是项目列表,第二个表示过滤器。筛选器表上的列可以包含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
如何以这种方式加入这些表?
答案 0 :(得分:2)
你可以尝试这样....
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))
答案 1 :(得分:1)
我认为您的意思是在您的加入CASE
子句中使用ON
表达式,如下所示
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