MySQL - 插入行同时避免重复

时间:2015-08-19 11:20:52

标签: mysql

我目前有两张桌子。一个相当大,一个适当小。 大桌子由表格中的许多插页组成,与小表格相同。

我想将小表中的记录(可能是使用 insert into )插入到大表 IF 中,它们还没有出现在大表中。

注意事项

1 个答案:

答案 0 :(得分:1)

您可以使用not exists

执行此操作
insert into bigTable(col1, . . ., coln)
   select col1, . . ., coln
   from smallTable s
   where not exists (select 1
                     from bigTable b
                     where b.col1 = s.col1 and b.col2 = s.col2 and . . .
                    );

注意:这不适用于NULL值。嗯,确实"工作",但是你会得到重复的行,这与NULL的含义一致,因为"未知" (而不是"缺少")。

相关问题