使用mysql中的左外连接删除行时出现问题

时间:2009-12-08 17:19:53

标签: mysql

似乎不能锻炼我在这里做错了什么

SELECT * FROM tbl_imagelabel LEFT OUTER JOIN tbl_image ON tbl_imagelabel.label_id = tbl_image.label_id WHERE tbl_image.label_id is NULL

显示我想要删除的确切行。但如果我改变SELECT * FROM到DELETE FROM它不起作用

DELETE FROM tbl_imagelabel LEFT OUTER JOIN tbl_image ON tbl_imagelabel.label_id = tbl_image.label_id WHERE tbl_image.label_id is NULL

6 个答案:

答案 0 :(得分:10)

您尝试使用该语法从单个查询中的多个表中删除。尝试更像的东西(这只是一个松散的例子,不是要优化或任何东西):

DELETE FROM tbl_imagelabel
WHERE label_id IN (
    SELECT tbl_imagelabel.label_id 
    FROM tbl_imagelabel 
    LEFT OUTER JOIN tbl_image 
        ON tbl_imagelabel.label_id = tbl_image.label_id 
    WHERE tbl_image.label_id IS NULL
)

答案 1 :(得分:10)

有关MySQL 5 +的进一步参考:

DELETE tbl1.* FROM tbl1 LEFT JOIN tbl2 USING(fld) WHERE tbl2.fld IS NULL;

它会删除使用 fld 作为加入的 TBL1 上的所有孤儿。

GL Paulo Bueno

答案 2 :(得分:6)

我相信如果没有显式连接,这会做同样的事情。

DELETE FROM tbl_imagelabel 
WHERE label_id NOT IN (SELECT label_id FROM tbl_image)

答案 3 :(得分:4)

DELETE FROM tbl_imagelabel 
where label_id IN
(
SELECT tbl_imagelabel.label_id FROM tbl_imagelabel 
LEFT OUTER JOIN tbl_image 
ON tbl_imagelabel.label_id = tbl_image.label_id WHERE tbl_image.label_id is NULL
)

假设label_id是唯一的主键。

答案 4 :(得分:3)

虽然这里给出的所有答案都提供了解决问题中给出的具体示例的替代方法,但它们都没有在delete语句中明确包含左外连接。为此,您需要“USING”语句,如下所示:

DELETE FROM til USING tbl_imagelabel as til LEFT OUTER JOIN tbl_image as ti 
ON til.label_id = ti.label_id WHERE ti.label_id is NULL

<强>参考文献:

答案 5 :(得分:0)

我在这里使用此查询删除孤立数据:

DELETE FROM table1 WHERE NOT EXISTS (SELECT * FROM table2 WHERE idtable1=idtable2)