MySQL插入和连接表的NOT IN条件



我想从一个表中插入数据,我不想在我的目标表中再次导入相同的日期数据。

例如-我有日期作为我的源和目标表的列,我不希望在我的目标表相同的日期数据。日期列在两个表中相同,列数在两个表中也相同

我怎样才能做到这一点?

最好的方法是这样使用NOT EXISTS:

INSERT INTO destination_table
select * 
from source_table s
where not exists
(select 1 from destination_table d where d.date = s.date)

筛选这些日期并插入

INSERT INTO destination_table
select a.* from source a
where a.date not in ( select date from destination_table)

您可以按如下方式创建目标表:

CREATE TABLE Destination (
ID int NOT NULL,
Property1 PropertyType, 
Property2 PropertyType,
etc.....
UniqueDate DATE,
UNIQUE (UniqueDate)
);

记住用您自己的属性和类型替换PropertyX和PropertyType,并重命名UniqueDate

这段代码将在你的日期列上设置一个UNIQUE约束。

最新更新