如何通过使用消除重复项的联接从另一个表中插入一个表

时间:2018-07-10 12:40:44

标签: mysql sql

我用完全相同的列创建了一个表AB

create or replace table a (
    a1 varchar(30),
    a2 int,
    a3 int
);

create or replace table b (
    b1 varchar(30),
    b2 int,
    b3 int
);

然后在每个值中插入2个值:

insert into a values ('abc', 1, 2);
insert into a values ('abd', 1, 2);

insert into b values ('abd', 1, 2);
insert into b values ('abe', 1, 2);

如何制作插入语句,使其仅插入B中表A中不存在的记录(例如通过使用join语句?)?

insert into table a (
    select * from b
    );

(无主键帮助)。 奖励点是仅检查两列是否相同(例如a1 != b1a2 != b2)。

谢谢!

3 个答案:

答案 0 :(得分:2)

这应该给您您所需要的:

insert into a 
select b.*
from b left join  a on a.a1 = b.b1 and a.a2 = b.b2
where a.a1 is null 

答案 1 :(得分:1)

尝试一下

insert int a
select * from b
where (b1, b2, b3) not in (select a1, a2, a3 from a)

答案 2 :(得分:1)

我会使用not exists

insert into a (a1, a2, a3)
     select b1, b2, b3
     from b 
     where not exists (select 1 from a where a1 = b.b1 and a2 = b.b2);