有没有办法让FULL OUTER JOIN表匹配正确的记录?

问题描述 投票:-1回答:2

我正在尝试使用FULL OUTER JOIN连接两个表,两个表具有不同的数据行,并且这两个表之间的列是相同的。

表2全外连接表1

表格1

ID名称付款金额 === ======== ===================== 1杰克10000 20000年5月2日 3 Amy 30000

表2

ID名称付款金额AccountID === ======== ==================== ============ 1杰克10000 000001 2 Amy 30000 000002

执行后显示的输出

id T1name T2name付款金额AccountID === ======== ======== ==================== =========== = 1 Jack Jack 10000 000001 5月2日艾米20000 000002 3 Amy 30000

我期望的输出

id T1name T2name付款金额AccountID === ======== ======== ==================== =========== = 1 Jack Jack 10000 000001 20000年5月2日 3 Amy Amy 30000 000002

该表是按付款金额订购的。

sql sql-server jointable full-outer-join
2个回答
3
投票
CREATE TABLE #Table1
    ([id] varchar(2), [name] varchar(4), [Payment Amount] int)

INSERT INTO #Table1
    ([id], [name], [Payment Amount])
VALUES
    ('S1', 'Jack', 10000),
    ('S2', 'May', 20000),
    ('S3', 'Amy', 30000)

CREATE TABLE #Table2
    ([id] varchar(2), [name] varchar(4), [Payment Amount] int)
;     
INSERT INTO #Table2
    ([id], [name], [Payment Amount])
VALUES
    ('X1', 'Jack', 10000),
    ('X2', 'Amy', 30000)

select A.id,A.name T1name ,isnull(B.name,'') T2name,A.[Payment Amount] from #Table1 A  left join #Table2 B on A.name=B.name
and A.[Payment Amount]=B.[Payment Amount]

产量

id  T1name  T2name  Payment Amount
S1  Jack    Jack      10000
S2  May               20000
S3  Amy     Amy       30000

0
投票

您应该始终使用主键(特别是键)或使用唯一键来JOIN。否则你会得到重复的值。名称列可能不是唯一的,您将获得笛卡尔积。在您的情况下,为了获得您想要的结果,您应该join on t1.name=t2.name

© www.soinside.com 2019 - 2024. All rights reserved.