2012-05-19 63 views
1

基本上,我有三個表DELETE FROM不工作的多個表 - 無能與MySQL

工作場所與字段ID(其中我要刪除相關聯的數據的一個),並且識別參與者一個participantlist_id名單。

participantlist - 只是LIST_ID和名稱

participantlist_links - 與LIST_ID和participant_id

,我試圖使用查詢是這樣的:

DELETE FROM workplaces, 
participantlist, 
participantlist_links 
WHERE workplaces.id = '8' AND 
     workplaces.participantlist_id = participantlist_links.list_id AND 
     workplaces.participantlist_id = participantlist.list_id 

,但我得到:

MySQL說:

1064 - 你h在您的SQL語法中發生錯誤;檢查對應於您的MySQL服務器版本的手冊,以便在第3行的WHERE workplaces.id ='8'和workplaces.participantlist_id = participant'處使用正確的語法。

任何想法?

SOLUTION:

DELETE t1, t2, t3 
    FROM workplaces AS t1 
    LEFT JOIN participantlist AS t2 ON t1.participantlist_id = t2.list_id 
    LEFT JOIN participantlist_links AS t3 ON t2.list_id = t3.list_id 
    WHERE t1.id = '8' 
+0

是否要刪除相關的行形式的所有3個表?或者僅從1張桌子?還是從2開始? –

回答

2

你有沒有考慮把ON DELETE CASCADE的外鍵? 這種方式從工作區中刪除行時,其他行也會自動刪除。

請參閱此鏈接瞭解更多信息: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

否則你就必須使用單獨的DELETE FROM查詢,將它們全部刪除。

在執行這些刪除操作時使用事務處理很明智。所以,如果有什麼差錯,你可以回滾所做的更改:

BEGIN TRANSACTION; 
DELETE FROM ......; 
DELETE FROM ......; 
COMMIT; 
+0

我使用myisam ... –

1

嘗試

DELETE workplaces, participantlist, participantlist_links FROM workplaces, 
participantlist, 
participantlist_links 
WHERE workplaces.id = '8' AND 
     workplaces.participantlist_id = participantlist_links.list_id AND 
     workplaces.participantlist_id = participantlist.list_id 
1

正如the manual提到的,DELETE的多表的形式有不同的語法,你正在使用的。你想:

DELETE workplaces, participantlist, participant_links 
FROM workplaces 
    JOIN participantlist 
    ON workplaces.participantlist_id = participantlist.list_id 
    JOIN participantlist_links 
    ON workplaces.participantlist_id = participantlist_links.list_id 
WHERE workplaces.id = '8'