Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all records of a table that are not referenced from another table

Tags:

sql

mysql

2 tables:
items(id, ...)
users(id, item_id, ...)

How do you delete all records in items that are not referenced from users?

like image 374
Emanuil Rusev Avatar asked Jun 19 '10 08:06

Emanuil Rusev


2 Answers

Beware that NOT IN may be really slow. Sometimes - surpringly enough - its faster to do something like this:

DELETE FROM items WHERE id IN
(SELECT id FROM items EXCEPT SELECT item_id FROM users)
like image 179
Janick Bernet Avatar answered Oct 30 '22 03:10

Janick Bernet


DELETE FROM items WHERE id NOT IN (SELECT item_id FROM users)

(uses a subquery to select all the item_ids from users and then deletes the records from items where id is not in the results of that subquery)

like image 36
mikej Avatar answered Oct 30 '22 03:10

mikej