-3

我需要对两个表进行内部连接,但是,我想知道如何解决这种情况:

如果第二个表中的字段为 NULL,他会与另一个字段进行内部连接。

你可以给我一个例子吗?

谢谢

4

4 回答 4

2

取决于您要达到的目标...

CREATE TABLE #X 
(
[Id] INT,
[Name] VARCHAR(100)
)
INSERT INTO #X VALUES
(1,'michaeljackson'),
(2,'jim'),
(3,'jill'),
(4,'j')

CREATE TABLE #Y 
(
[Id] INT,
[AlternateId] INT,
[Score] INT
)
INSERT INTO #Y VALUES
(1,1,10),
(2,2,20),
(3,3,30),
(4,4,40),
(NULL,2,50)

--will join all of the records in #x to the null record
SELECT *
FROM   #X x
       INNER JOIN #Y y
       ON 
       x.Id = COALESCE(y.Id,x.Id)

--will join just to the ID = 4 record
SELECT *
FROM   #X x
       INNER JOIN #Y y
       ON 
       x.Id = COALESCE(y.Id,4)


--redirect and let join use alternative field
SELECT *
FROM   #X x
       INNER JOIN #Y y
       ON 
       x.Id = COALESCE(y.Id,y.AlternateId)

--maybe you want to actually do a FULL OUTER JOIN!
SELECT  *
FROM    #X x
    FULL OUTER JOIN #Y y
    ON 
    x.Id = y.Id
于 2013-03-19T20:15:34.127 回答
1

最容易将第二个表视为两个不相交的表,如下所示:

select *
from a
join (
    select NewKey = key1, * from b where b.key1 is null
  union all
    select NewKey = key2, * from b where b.key1 is not null
) b on b.NewKey = a.key
于 2013-03-19T18:29:48.260 回答
1

我相信以下内容应该可以充分发挥作用。

SELECT *
  FROM tblA a
    INNER JOIN tblB b ON (b.Col1 IS NOT NULL AND b.Col1 = a.Col1) OR (b.Col1 IS NULL AND b.Col2 = a.Col2)

如果 b.Col1 不为 NULL,则它加入 Col1,否则如果它为 NULL,则它加入 Col2。

于 2013-03-19T18:31:09.000 回答
1

试试这个:

    select * from a 
    inner join b on 
    (case when b.columntojoin is null then b.alternatecolumn else b.columntojoin end) 
    = a.columntojoin
于 2013-03-19T18:51:32.767 回答