【问题标题】:sql - how to insert on table1 from table2 but dont insert the duplicate valuesql - 如何从table2插入table1但不插入重复值
【发布时间】:2016-07-21 22:38:33
【问题描述】:

我有 2 个表,table1 和 table2,每个表都添加了行 table1 = 2m 行和 table2 = 1m 行并且 table2 中的一些行已经在 table1 上,并且 table1 具有唯一值

我试试这个命令:

INSERT INTO table1 (top1, top2, top3)
  SELECT top1, top2, top3 FROM table2

top1 是唯一值,如果 table2 top1 已经在 table1 top1 上,我该如何选择?

【问题讨论】:

  • 什么是PK,就是top1或者top1+top2+top3

标签: sql


【解决方案1】:

有几种方法可以做到这一点,一些不同的数据库提供了更简单的方法。这是not exists 的通用解决方案:

INSERT INTO table1 (top1, top2, top3)
SELECT top1, top2, top3 FROM table2 t2
WHERE NOT EXISTS (
    select 1 
    from table1 t1 
    where t1.top1 = t2.top1)

另一个带有outer join \ null 检查的通用选项:

insert into table1 (top1, top2, top3)
select t2.top1, t2.top2, t2.top3
from table2 t2 
   left join table1 t1 on t2.top1 = t1.top1
where t1.top1 is null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多