SQL INSERT缺少表A到表B中的行

时间:2021-12-24 01:58:07

I'm trying to insert rows into table 'Data' if they don't already exist.

我试图在表'数据'中插入行,如果它们尚不存在的话。

For each row in Export$, I need the code to check 'Data' for rows that match both Period (date) and an ID (int) - if the rows don't already exist then they should be created.

对于Export $中的每一行,我需要代码来检查“数据”以查找与Period(日期)和ID(int)匹配的行 - 如果这些行尚不存在则应创建它们。

I'm pretty sure my 'NOT EXISTS' part is wrong - what's the best way to do this? Thanks for all your help

我很确定我的“不存在”部分是错误的 - 这是最好的方法吗?感谢你的帮助

    IF NOT EXISTS (SELECT * FROM Data, Export$ WHERE Data.ID = Export$.ID AND Data.Period = Export$.Period)
    INSERT INTO Data (Period, Performance, ID)
    SELECT Period, [Return], [ID] FROM Export$

2 个解决方案

#1


10  

try this:

尝试这个:

INSERT INTO Data (Period, Performance, ID)
SELECT Period, [Return], [ID] 
FROM Export$ e
where not exists (
select *
from Data
where  ID = e.ID and Period = e.Period)

#2


5  

try something like, will need tweaking to fit your tables

尝试类似的东西,需要调整以适应您的表格

insert into data
select * from export
left join data on data.id = export.id
                     and data.period = export.period
where data.id is null

#1


10  

try this:

尝试这个:

INSERT INTO Data (Period, Performance, ID)
SELECT Period, [Return], [ID] 
FROM Export$ e
where not exists (
select *
from Data
where  ID = e.ID and Period = e.Period)

#2


5  

try something like, will need tweaking to fit your tables

尝试类似的东西,需要调整以适应您的表格

insert into data
select * from export
left join data on data.id = export.id
                     and data.period = export.period
where data.id is null