Sql join和insert如果不存在

时间:2014-08-14 17:10:06

标签: sql sql-server sql-server-2008

我有一个名为Itemlookup的表,我想从两个表中插入值。但是,如果Itemlookup没有这些值,我只想插入它。我可以插入到表中但是如果我再次执行它,它会再次插入。我想避免这样做。

我试过使用If not exists,但没有运气。任何帮助都非常感谢。

Insert into Itemlookup (ItemNumber, Cases, Shift, [TimeStamp])

Select a.ItemNumber, b.CaseCount, a.TimeStamp 
from ItemsProduced a innerjoin     
       MasterItemList b on a.ItemNumber=b.ItemNumber

3 个答案:

答案 0 :(得分:4)

尝试left join

Insert into Itemlookup (ItemNumber, Cases, [TimeStamp])
Select a.ItemNumber, b.CaseCount, a.TimeStamp 
from ItemsProduced a 
inner join MasterItemList b on a.ItemNumber = b.ItemNumber
left join Itemlookup i on i.ItemNumber = a.ItemNumber
                      and i.Cases= b.CaseCount
                      and i.TimeStamp = a.TimeStamp 
where i.ItemNumber is null

BTW你的插入包含4列而你的选择只有3.我删除了Shift以保持一致性。

答案 1 :(得分:1)

如果你有兴趣,这是使用NOT EXISTS的正确方法(同时删除" Shift"如juergen所做的那样):

Insert into Itemlookup (ItemNumber, Cases, [TimeStamp])
Select a.ItemNumber, b.CaseCount, a.TimeStamp 
from ItemsProduced a 
inner join MasterItemList b on a.ItemNumber = b.ItemNumber
WHERE NOT EXISTS(
  SELECT * FROM Itemlookup 
  WHERE ItemNumber=a.ItemNumber
  AND Cases=b.CaseCount
  AND [TimeStamp]=a.TimeStamp
)

答案 2 :(得分:0)

Insert into Itemlookup (ItemNumber, Cases, Shift, [TimeStamp])
Select a.ItemNumber, b.CaseCount,ColumnName, a.TimeStamp 
from ItemsProduced a innerjoin     
       MasterItemList b on a.ItemNumber=b.ItemNumber
where a.ItemNumber NOt In (Select T.ItemNumber From Itemlookup T)