SQL DELETE与JOIN另一个表用于WHERE条件

时间:2009-12-30 15:27:50

标签: mysql sql delete-row sql-delete mysql-error-1093

我必须从guide_category中删除与guide表(死关系)无关的行。

这是我想要做的,但它当然不起作用。

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)

错误:

  

您无法在FROM子句

中为更新指定目标表'guide_category'

4 个答案:

答案 0 :(得分:105)

由于锁定实施问题,MySQL不允许使用DELETEUPDATE引用受影响的表格。

您需要在此处设置JOIN

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

或只使用NOT IN

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

答案 1 :(得分:9)

我认为,根据您的描述,以下内容就足够了:

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

我假设,所涉及的表没有参照完整性约束,是吗?

答案 2 :(得分:4)

尝试使用此示例SQL脚本以便于理解,

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

你的案子是:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

答案 3 :(得分:-3)

怎么样:

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

  )