1

I try to do 2 delete queries in one. For example:

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

I tried using a single query:

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

That works well if in table comments exist records with article_id 4, but doesn't remove articles records with articles.id = 4, if in comments records with article_id = 4 not found. Is there any way to do that?

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Harry
  • 334
  • 5
  • 12
  • 2
    you really should take a look on constraints. see http://stackoverflow.com/questions/3433975/why-use-foreign-key-constraints-in-mysql – Rufinus Mar 13 '12 at 11:37

3 Answers3

4

This will do it -

DELETE `articles`, `comments`
FROM `articles`
LEFT JOIN `comments`
    ON `articles`.`id` = `comments`.`article_id`
WHERE `articles`.`id` = 4;
user1191247
  • 10,808
  • 2
  • 22
  • 32
  • This will also delete `articles` that have no `comments`. This answers the question more exactly. – sulai Sep 13 '13 at 12:35
1

Try the following:

DELETE FROM `articles`, `comments` 
USING `articles` INNER JOIN `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
Korhan Ozturk
  • 11,148
  • 6
  • 36
  • 49
0

Use this

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

or

DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
RN Kushwaha
  • 2,081
  • 3
  • 29
  • 40