Full Outer Join关联异常:如何实现指定字段匹配的目标合并结果?
问题描述
现有两张数据表 tableA 和 tableB,结构及数据如下:
tableA
| porow | sorow | poid | soid | poreference | posource | poprice | sopriceconfirm |
|---|---|---|---|---|---|---|---|
| 1 | 214446 | 215712 | AAA | PO | 50 | 1 | |
| 1 | 215355 | 217902 | BBB | PO | -60 | 0 |
tableB
| porow | sorow | poid | soid | poreference | sosource | soprice | sopriceconfirm |
|---|---|---|---|---|---|---|---|
| 1 | 214446 | 215712 | AAA | SO | -190 | 0 | |
| 1 | 215355 | 217902 | BBB | SO | 0 | 0 |
期望合并结果
| porow | sorow | poid | soid | poreference | posource | poprice | sosource | soprice | sopriceconfirm |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 214446 | 215712 | AAA | PO | 50 | SO | -190 | 1 |
| 1 | 1 | 215355 | 217902 | BBB | PO | -60 | SO | 0 | 0 |
当前执行的SQL(返回多余行)
select b.[porow], a.[sorow], b.poid, a.soid, b.[poreference], b.[posource], a.[poprice], a.[sosource], b.[soprice], a.[sopriceconfirm] from tableA a full outer join tableB b on a.[sorow] = b.[porow]
问题核心:当前SQL仅用a.[sorow] = b.[porow]作为关联条件,但这两个字段在两张表中均为空或固定值1,导致所有行互相匹配产生笛卡尔积,出现多余行。仅移除单表的BBB记录时匹配行数少,问题不明显;同时存在时匹配逻辑错误就会暴露。
解决方法
需要使用精准的业务关联键来匹配对应行,以下两种方案均可实现目标:
方案1:用唯一标识字段关联(最可靠)
通过poreference+poid+soid这组唯一标识字段关联,确保每行精准匹配:
select a.porow, b.sorow, a.poid, a.soid, a.poreference, a.posource, a.poprice, b.sosource, b.soprice, a.sopriceconfirm from tableA a inner join tableB b on a.poreference = b.poreference and a.poid = b.poid and a.soid = b.soid
方案2:按业务规则的字段关联
如果业务上要求通过poreference+porow+sorow匹配,注意tableA的porow对应tableB的sorow,结合poreference匹配:
select a.porow, b.sorow, a.poid, a.soid, a.poreference, a.posource, a.poprice, b.sosource, b.soprice, a.sopriceconfirm from tableA a inner join tableB b on a.poreference = b.poreference and a.porow = b.sorow
内容的提问来源于stack exchange,提问作者Newstar
相关产品推荐
相关产品推荐

