Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DELETE values from one table with id that doesn't exist in another in mysql

Tags:

sql

mysql

I have recently started using relations between tables, and when I tried to connect 2 I found that there are some IDs that have nonexistent foreign keys.

For this issue lets assume I have restaurants table with id and name, and menus table with id rest_id that is a foreign key from the restaurant table.

I wanna delete all the menus that has rest_id that doesn't exist in restaurants table.

I used this:

DELETE FROM `Menus` WHERE restid IN (SELECT DISTINCT `restid` from 
   `Menus` M left join `Eng_Restaurants` ER on M.`restid` = ER.`ID`
where ER.`ID` is null)

But I got the following error: #1093 - You can't specify target table 'Menus' for update in FROM clause.

Note that the subquery does return the ids that doesn't exist in restaurants table:

(SELECT DISTINCT `restid` from 
       `Menus` M left join `Eng_Restaurants` ER on M.`restid` = ER.`ID`
    where ER.`ID` is null)

Any ideas?

like image 588
Jacob Cohen Avatar asked Oct 26 '13 11:10

Jacob Cohen


People also ask

Can you remove rows from a table based on values from another table?

Deleting rows based on another table. Sometimes we need to delete rows based on another table. This table might exist in the same database or not. We can use the table lookup method or SQL join to delete these rows.

Can delete work without WHERE clause?

Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

Can delete have WHERE clause?

You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.


1 Answers

You do not need to make a JOIN in your subquery:

DELETE FROM Menus
WHERE restid NOT IN (SELECT id FROM Eng_Restaurants)
like image 115
Guillaume Poussel Avatar answered Oct 12 '22 07:10

Guillaume Poussel