2009-04-09 57 views
7

我試圖用SQL從多個表中刪除多個表,這些表都是 聯合在一起的。刪除多個表中的行

表A被連接到表B 表B被接合到表C

我想刪除的所有行表B中&Ç對應於一個行表A

CREATE TABLE `boards` (
    `boardid` int(2) NOT NULL AUTO_INCREMENT, 
    `boardname` varchar(255) NOT NULL DEFAULT '', 
    PRIMARY KEY (`boardid`) 
); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `messages` 
-- 

CREATE TABLE `messages` (
    `messageid` int(6) NOT NULL AUTO_INCREMENT, 
    `boardid` int(2) NOT NULL DEFAULT '0', 
    `topicid` int(4) NOT NULL DEFAULT '0', 
    `message` text NOT NULL, 
    `author` varchar(255) NOT NULL DEFAULT '', 
    `date` datetime DEFAULT NULL, 
    PRIMARY KEY (`messageid`) 
); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `topics` 
-- 

CREATE TABLE `topics` (
    `topicid` int(4) NOT NULL AUTO_INCREMENT, 
    `boardid` int(2) NOT NULL DEFAULT '0', 
    `topicname` varchar(255) NOT NULL DEFAULT '', 
    `author` varchar(255) NOT NULL DEFAULT '', 
    PRIMARY KEY (`topicid`) 
); 

回答

18

好吧,如果你已經使用InnoDB表,你可以建立一個cascading delete with foreign keys會自動做這一切。但是,如果你有一些理由使用MyISAM的,你只需要使用一個multiple-table DELETE

DELETE FROM boards, topics, messages 
USING boards INNER JOIN topics INNER JOIN messages 
WHERE boards.boardid = $boardid 
    AND topics.boardid = boards.boardid 
    AND messages.boardid = boards.boardid; 
+0

爲什麼「使用」而不是「打開」? – pingu 2013-11-08 12:01:11

2

你既可以只檢查是否存在

delete from topics where boardid in (select boardid from boards) 
delete from messages where boardid in (select boardid from boards) 

,但是這隻會意義,如果這種行爲不應該總是適用。當行爲應該始終適用,落實級聯刪除外鍵

在無數的網站解釋說,在您的幫助文檔和here

1

從多個表中刪除行可以通過兩種方式來完成:

  • 從一個表中刪除行,通過參考另一個表來確定要刪除的行 表
  • 使用單個語句從多​​個表中刪除行

多表DELETE語句可以寫成兩種格式。下面的例子說明一個語法,用於從一個表t1刪除行的查詢,其中id值匹配在一個表t2:

DELETE t1 FROM t1, t2 WHERE t1.id = t2.id; 

第二語法稍有不同:

DELETE FROM t1 USING t1, t2 WHERE t1.id = t2.id; 

要從兩個表中刪除匹配的記錄,該語句是:

DELETE t1, t2 FROM t1, t2 WHERE t1.id = t2.id; 
DELETE FROM t1, t2 USING t1, t2 WHERE t1.id = t2.id; 

的ORDER BY和LIMIT子句通常由支持UPDATE和DELETE不準時這些語句用於多表操作。