繁体   English   中英

如何正常连接两列上的两个表,但如果其中一列包含null,那么结果必须包含仅与另一列匹配的行?

[英]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))

Sql小提琴

我认为你的意思是在你的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM