2

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)

2
  • 1
    Something like: INSERT INTO tableA (field1, field2) SELECT b.field1, b.field2 FROM tableA a LEFT JOIN tableB b USING field1 WHERE a.field1 IS NULL I think is what you're looking for. Start off by figuring out the SELECT that you want (all rows from tableB that are not in tableA), and then insert only those rows. Commented Jan 3, 2021 at 4:06
  • question uri trymysql:lab2017:basicops:uu579distantaystipulate Commented Feb 4, 2021 at 21:04

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.