Jeaf Gilbert
Jeaf Gilbert

Reputation: 12021

MySQL: Delete row if id doesn't exist in other table

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.

Upvotes: 5

Views: 5755

Answers (1)

genesis
genesis

Reputation: 50982

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

Upvotes: 11

Related Questions