mysql 根据 select 从一个 table 插入到另一个
mysql insert from one table to another based on select
假设我们有
Table一个
field 1 | field 2
orange | fruit
apple | fruit
和
Table B
field 1 | field 2
orange | fruit
lemon | fruit
并且只想插入从 Table B 到 Table A 的在字段 1 上不匹配的行,以便 Table A 变为:
Table一个
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)
此查询后 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
);
假设我们有
Table一个
field 1 | field 2
orange | fruit
apple | fruit
和
Table B
field 1 | field 2
orange | fruit
lemon | fruit
并且只想插入从 Table B 到 Table A 的在字段 1 上不匹配的行,以便 Table A 变为:
Table一个
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)
此查询后 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
);