让我们说我有两张桌子:
table 1 columns: A,B,C
table 2 columns: D,E,F
JOIN Conditions
table1.A = table2.D, table1.B=table2.E, table1.C = table2.F
任何列都可以具有空值。我希望将null值视为任何值的匹配项。 (即,如果A = D且B = E,但C为空.F有两个值,A = D,B = E.两行应包括在结果表中)
Table1: Table2:
A: B: C: D: E: F:
a b c a b c
e <null> f e a f
o <null> q e b f
h i j h i k
l <null> m l a m
o <null> q o <null> q
results(show table 2 values...):
D: E: F:
a b c
e a f
e b f
o <null> q
l a m
答案 0 :(得分:2)
我会使用类似于JNevill的方法,但我会发现这样做是为了让我更有意义:
ON (Table1.A=Table2.D OR Table1.A IS NULL OR Table2.D IS NULL)
AND (Table1.B=Table2.E OR Table1.B IS NULL OR Table2.E IS NULL)
AND (Table1.C=Table2.F OR Table1.C IS NULL OR Table2.F IS NULL)
答案 1 :(得分:1)
你可以写出这个条件。我觉得可能有一些方法可以做到这一点更多偷偷摸摸/更简洁,但这应该让你在球场:
ON
(table1.A = table2.D AND table1.B = table2.E AND (table1.C = table2.F OR table1.C IS NULL))
OR (table1.A = table2.D AND (table1.B = table2.E OR table1.B IS NULL) AND table1.C = table2.F)
OR ((table1.A = table2.D OR table1.A IS NULL) AND table1.B = table2.E AND table1.C = table2.F)
答案 2 :(得分:1)
我认为这可以满足您的需求。 SQL实际上会相当有效地优化它。
DECLARE @t1 AS TABLE
(
[A] NVARCHAR(25)
, [B] NVARCHAR(25)
, [C] NVARCHAR(25)
);
DECLARE @t2 AS TABLE
(
[D] NVARCHAR(25)
, [E] NVARCHAR(25)
, [F] NVARCHAR(25)
);
INSERT INTO @t1
([A]
, [B]
, [C])
VALUES (N'one',N'one',N'one'),
(N'two',N'two',NULL),
(N'three',N'three',N'three');
INSERT INTO @t2
([D]
, [E]
, [F])
VALUES (N'one',N'one',N'one'),
(N'two',N'two',NULL),
(N'three',N'three',NULL);
SELECT *
FROM @t1 AS [t1]
JOIN @t2 AS [t2]
ON [t1].[A] = [t2].[D]
AND [t1].[B] = [t2].[E]
AND [t1].[C] = [t2].[F];
SELECT *
FROM @t1 AS [t1]
JOIN @t2 AS [t2]
ON
(
[t1].[A] = [t2].[D]
OR [t1].[A] IS NULL
OR [t2].[D] IS NULL
)
AND
(
[t1].[B] = [t2].[E]
OR [t1].[B] IS NULL
OR [t2].[E] IS NULL
)
AND
(
[t1].[C] = [t2].[F]
OR [t1].[C] IS NULL
OR [t2].[F] IS NULL
)
;