SQL left join 数据重复

2024-11-24 18:35:54
推荐回答(2个)
回答1:

1、Select 语句 加 Distinct

2、考虑部分记录可能已经存在于 Test 表,所以 Insert into Test 的时候 加个 Where 语句
例如
Insert Into Test (itemno,f_itemno)
select distinct bg.goodsCode as itemno,isnull(bg2.goodsCode,'0000') as f_itemno
from [MESBT].[dbo].[SJ_nParts] sn
--查询本级物料及数量
left join [MESBT].[dbo].[BK_goods] bg on sn.goodsId=bg.goodsId
--查询上级物料
left join [MESBT].[dbo].[SJ_nParts] sn2 on sn2.parentId=sn.partId
left join [MESBT].[dbo].[BK_goods] bg2 on sn2.goodsId=bg2.goodsId
Left Join Test t On bg.goodsCode = t.itemno And isnull(bg2.goodsCode,'0000') = t.f_itemno
Where t.itemno is null And t.f_itemno is null

回答2:

select distinct 再加上后面那段