2012-03-13 59 views
1

我嘗試在一箇中刪除查詢。例如:MySQL多表刪除語法

DELETE FROM `comments` WHERE `article_id` = 4; 
DELETE FROM `aricles` WHERE `id` = 4; 

我試圖用一個單一的查詢:

DELETE `articles`, `comments` 
FROM `articles` INNER JOIN `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4 

如果表comments存在的記錄與article_id 4行之有效,但不與articles刪除articles記錄。 id = 4,如果在comments記錄中article_id = 4未找到。有沒有辦法做到這一點?

+2

你真的應該看看約束。請參閱http://stackoverflow.com/questions/3433975/why-use-foreign-key-constraints-in-mysql – Rufinus 2012-03-13 11:37:11

回答

4

這將做到這一點 -

DELETE `articles`, `comments` 
FROM `articles` 
LEFT JOIN `comments` 
    ON `articles`.`id` = `comments`.`article_id` 
WHERE `articles`.`id` = 4; 
+0

這也會刪除沒有「評論」的「文章」。這更準確地回答了這個問題。 – sulai 2013-09-13 12:35:28

1

嘗試以下操作:

DELETE FROM `articles`, `comments` 
USING `articles` INNER JOIN `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4 
+0

這將*不*刪除沒有'評論'的'文章'。 – sulai 2013-09-13 12:34:02

0

使用此

DELETE FROM `articles`, `comments` 
USING `articles`,`comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4 

DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4