2009-12-08 101 views
8

加入似乎無法鍛鍊什麼即時做錯了問題刪除行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 tbl_imagelabel LEFT OUTER JOIN tbl_image ON tbl_imagelabel.label_id = tbl_image.label_id WHERE tbl_image.label_id is NULL

+0

是否有錯誤訊息? – Bobby 2009-12-08 17:22:47

+0

在'DELETE'查詢前運行'EXPLAIN EXTENDED'並在此處粘貼輸出。 – 2009-12-08 17:26:29

回答

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 
) 
+0

34秒使所有區別:-) – cdonner 2009-12-08 17:27:28

+0

LoL ...我知道... +1爲解決方案的任何一種方式:D – 2009-12-08 17:28:24

+0

高興地返回優惠:-) – cdonner 2009-12-08 17:28:56

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是唯一的主鍵。

6

我相信這沒有明確的聯接做同樣的事情。

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

+1好抓! (黨15個字符限制評論) – 2009-12-08 17:33:12

3

雖然這裏給出的所有的答案提供瞭解決這個問題給出了具體的例子的替代手段,他們都這樣做實際上不包括左外DELETE語句明確地加入。要做到這一點,你需要的 '使用' 聲明如下:

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 

參考文獻:

8

獲得進一步的參考,在MySQL 5+:

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

它會刪除任何orph ans on TBL1使用fld as join。

GL Paulo Bueno