I think this is newbie ask. How to delete row if id doesn't exist in other table? My thought is fetch the ids first and delete. I'm looking for better querying.
1 Answer
You can set foreign keys to these tables.
More info here
for simple query, here it is:
DELETE FROM table WHERE (SELECT count(1) FROM table2 WHERE id = table.id) < 1
2 Comments
Liam
I also found this useful - thank you. I knew it would be a subquery, but I couldn't think how to write it. Edit, for those interested I'm using MySQL.
Yogster
Is there any reason why you used
COUNT? That query will have to go through all of table2's rows to count how many occurrences of id there are. Using EXISTS would have been a lot more efficient as the query would stop as soon as it finds the first ocurrence: DELETE FROM table WHERE NOT EXISTS (SELECT 1 FROM table2 WHERE id = table.id)