2012-11-20 30 views
2

試圖刪除由單個語句中的子選擇生成的id列表。這可能嗎?我一直在嘗試以下:子選擇在一個where-in子句中

[編輯]修正查詢

DELETE from store 
WHERE id in (SELECT store.id 
       FROM storeInfo 
       JOIN store ON storeInfo.store_id = store.id 
       WHERE storeInfo.type = 17) 

但是,這是不正確的語法...不知道如何正確建立這個。

+2

什麼是對'storeInfo'的'JOIN'的目的是什麼?你沒有在子查詢的「SELECT」或「WHERE」中使用它。 'store.type'應該是'storeInfo.type'嗎? –

+0

爲什麼你不只是有「從商店 WHERE store.type = 17」刪除,因爲你反正沒有使用storeInfo表 – randominstanceOfLivingThing

+0

抱歉,在這裏輸入了一個錯誤。 'type'在信息表中 – Will

回答

2
DELETE store 
FROM store 
JOIN storeInfo 
    ON storeInfo.store_id = store.id 
WHERE storeInfo.type = 17 
+0

+1。刪除連接。好的方法。 – danihp

2

錯字更新的問題後 - 你不需要在子查詢一個JOIN。您可以從IN()子查詢中返回storeInfo.store_id

DELETE FROM `store` WHERE `id` IN (SELECT `store_id` FROM `storeInfo` WHERE `type` = 17) 

的MySQL不會允許您使用表store子查詢,然後從中刪除行。但是,您可以使用storeInfo,因爲它可以直接與store_id連接。

如果需要從刪除這些表都(例如,如果在storeInfo行成爲當他們的父母從store刪除孤立的),使用JOIN語法來代替:

DELETE 
    /* Syntax to delete rows from both tables */ 
    store, storeInfo 
FROM 
    store JOIN storeInfo ON store.id = storeInfo.store_id 
WHERE storeInfo.type = 17 

回顧MySQL DELETE syntax reference的全部細節。

+0

+1 - 我不知道MySql具有多表刪除功能... –

+0

@MichaelFredrickson仔細使用它!我認爲我在實踐中並沒有真正使用它。 (剛剛在我的測試數據庫中證實,它不會完全錯誤) –

0

你可以直接加入到delete

delete store from store 
    JOIN storeInfo ON storeInfo.store_id = store.id 
    WHERE store.type = 17;