如果左侧字段为空,则左连接并使用左侧字段,否则使用右侧字段

时间:2018-06-05 23:34:26

标签: sql ms-access

使用C#中的Access驱动程序。

我试图离开加入,右边的字段会覆盖左边的字段,但前提是存在正确的字段。到目前为止,我有这个,它总是覆盖左边的字段,因为左边的Col1和Col2被忽略:

SELECT LeftAlias.PartNumber AS PartNumber, Col1, Col2, Col3
INTO TableA FROM 
(SELECT PartNumber, Col3 FROM TableA IN 'LeftFile.mdb') AS LeftAlias
LEFT JOIN
(SELECT PartNumber, Col1, Col2 FROM TableA IN 'RightFile.mdb') AS RightAlias
ON LeftAlias.PartNumber=RightAlias.PartNumber
ORDER BY LeftAlias.PartNumber;


LeftFile.TableA
PartNumber | Col1   | Col2  | Col3
-----------+--------+-------+------
123-abc    | cat    | dog   | 10
456-def    | horse  | zebra | 11
789-ghi    | ameoba | mouse | 12

RightFile.TableA
PartNumber | Col1   | Col2
-----------+--------+-----
123-abc    | lion   | hyena
456-def    | <null> | <null>

Desired output TableA
PartNumber | Col1   | Col2  | Col3
-----------+--------+-------+-------
123-abc    | lion   | hyena | 10
456-def    | horse  | zebra | 11
789-ghi    | amoeba | mouse | 12

如果RightFile中存在该字段,我该如何获得覆盖? 我加入的PartNumber永远不会为NULL。

1 个答案:

答案 0 :(得分:1)

您的查询应该是这样的:

SELECT LeftAlias.PartNumber AS PartNumber, 
       IIF(ISNULL(RightAlias.Col1), LeftAlias.Col1, RightAlias.Col1) AS Col1, 
       IIF(ISNULL(RightAlias.Col2), LeftAlias.Col2, RightAlias.Col2) AS Col2, 
       LeftAlias.Col3
INTO TableA FROM 
(SELECT PartNumber, Col1, Col2, Col3 FROM TableA IN 'LeftFile.mdb') AS LeftAlias
LEFT JOIN
(SELECT PartNumber, Col1, Col2 FROM TableA IN 'RightFile.mdb') AS RightAlias
ON LeftAlias.PartNumber=RightAlias.PartNumber
ORDER BY LeftAlias.PartNumber;

IIF函数将第一个参数计算为表达式,如果表达式为true,则返回第二个参数;如果表达式为false,则返回第三个参数。 ISNULL返回true或false,具体取决于作为参数传递的值是否为null

请注意,如果使用Access 2007或更高版本,您可以缩短这些行:

IIF(ISNULL(RightAlias.Col1), LeftAlias.Col1, RightAlias.Col1) AS Col1, 
IIF(ISNULL(RightAlias.Col2), LeftAlias.Col2, RightAlias.Col2) AS Col2, 

使用Nz function

Nz(RightAlias.Col1, LeftAlias.Col1) AS Col1, 
Nz(RightAlias.Col2, LeftAlias.Col2) AS Col2,