Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete records not present in join

Imagine two tables (A and B):

A        B
1        2
2        3 
6        5 
4        7
9        11
         13
         23
         9 

Now I want to delete records from A that are not present in B, e.g deleting 1, 6 and 4 from A.

My initial idea is that you could 'negate' the results of a join.

like image 390
abcde123483 Avatar asked Dec 13 '22 11:12

abcde123483


2 Answers

DELETE FROM A WHERE NOT EXISTS (SELECT * FROM B WHERE A.id = B.id)

I've assumed that those columns are named id.

like image 74
Peter Alexander Avatar answered Dec 30 '22 21:12

Peter Alexander


An alternative to the NOT EXISTS answer:

DELETE FROM A WHERE id NOT IN (SELECT id FROM b);

Again, assuming the column is named id.

like image 24
Michael Berkowski Avatar answered Dec 30 '22 21:12

Michael Berkowski