76

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

Sam
  • 7,252
  • 16
  • 46
  • 65
hsz
  • 148,279
  • 62
  • 259
  • 315

4 Answers4

112

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
        )
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
9

I think, from your description, the following would suffice:

DELETE FROM guide_category 
WHERE id_guide NOT IN (SELECT id_guide FROM guide)

I assume, that there are no referential integrity constraints on the tables involved, are there?

Dirk
  • 30,623
  • 8
  • 82
  • 102
  • 1
    this will be a little bit slow as it will execute a (SELECT id_guide FROM guide) for every entry – Toumi Oct 12 '16 at 12:51
  • That actually depends, @Toumi. The query planner/optimizer can do a lot behind the scenes here. – Dirk Oct 12 '16 at 16:53
5

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL
hsz
  • 148,279
  • 62
  • 259
  • 315
user2384628
  • 71
  • 1
  • 1
-3

How about:

DELETE guide_category  
  WHERE 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

  )
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
  • That's the original query and has the exact same problem of referencing the original table in a derived table expression. – siride Aug 17 '14 at 14:38