简体   繁体   中英

mysql insert from one table to another based on select

Supposing we have

Table A

field 1 | field 2

orange  | fruit
apple   | fruit

and

Table B

field 1 | field 2

orange  | fruit
lemon   | fruit 

And want to insert only the rows from Table B to Table A that don't match on field 1 so that Table A becomes:

Table A

field1  | field2

orange  | fruit
apple   | fruit
lemon   | fruit

Ive tried

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)

(no insert)

and

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

(incorrect insert)

You don't have your NOT EXISTS expression quite right, it needs to look at the value from tableB that you are trying to insert:

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 after this query:

field1  field2
orange  fruit
apple   fruit
lemon   fruit

Demo on db-fiddle

you can simply use union for that or use below code

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)

This is probably not the best solution, but this solution using joins worked for me:

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM