[英]mysql insert from one table to another based on select
假设我们有
表 A
field 1 | field 2
orange | fruit
apple | fruit
和
表 B
field 1 | field 2
orange | fruit
lemon | fruit
并且只想将表 B 中与字段 1 上不匹配的行插入表 A,以便表 A 变为:
表 A
field1 | field2
orange | fruit
apple | fruit
lemon | fruit
我试过了
insert into tableA (field1, field2)
select field1, field2 from tableB
where not exists
(select * from tableA as a join tableB as b on a.field1 = b.field1)
(没有插入)
和
insert into tableA (field1, field2)
select field1, field2 from tableA as a left join tableB as b on a.field1 = b.field1
union
select field1, field2 from tableA as s right join tableB as b on a.field1 = b.field1
where a.field1 != b.field1
(错误插入)
您的NOT EXISTS
表达式不太正确,它需要查看您尝试插入的tableB
中的值:
INSERT INTO tableA (field1, field2)
SELECT field1, field2
FROM tableB b
WHERE NOT EXISTS (SELECT * FROM tableA a WHERE a.field1 = b.field1)
Output of SELECT * FROM tableA
查询后:
field1 field2
orange fruit
apple fruit
lemon fruit
你可以简单地使用 union 或使用下面的代码
INSERT INTO Table A SELECT * FROM Table B
WHERE NOT EXISTS (SELECT 1 FROM TABLE A Data
WHERE A.field1 = Data.field1 AND
A.field2 = Data.field2)
这可能不是最好的解决方案,但这个使用连接的解决方案对我有用:
INSERT INTO A(F1,F2)
SELECT *
FROM A NATURAL RIGHT JOIN B AS TAB
WHERE TAB.F1 NOT IN (
SELECT F1
FROM A NATURAL JOIN B
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.