Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL DELETE with JOIN another table for WHERE condition

I have to delete rows from guide_category that have no relation with guide table (dead relations).

Here is what I want to do, but it of course does not work.

DELETE FROM guide_category AS pgc   WHERE pgc.id_guide_category IN (SELECT id_guide_category                                     FROM guide_category AS gc                               LEFT JOIN guide AS g ON g.id_guide = gc.id_guide                                   WHERE g.title IS NULL) 

Error:

You can't specify target table 'guide_category' for update in FROM clause

like image 387
hsz Avatar asked Dec 30 '09 15:12

hsz


1 Answers

Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE.

You need to make a JOIN here instead:

DELETE  gc.* FROM    guide_category AS gc  LEFT JOIN         guide AS g  ON      g.id_guide = gc.id_guide WHERE   g.title IS NULL 

or just use a NOT IN:

DELETE   FROM    guide_category AS gc  WHERE   id_guide NOT IN         (         SELECT  id_guide         FROM    guide         ) 
like image 69
Quassnoi Avatar answered Sep 27 '22 23:09

Quassnoi