Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF row exists THEN delete row in mysql

I have a query like this:

IF EXISTS(SELECT 1 FROM table1 WHERE col1 = ? LIMIT 1) THEN
DELETE FROM table2 WHERE col2 = ?
END IF

But I don't know why above query does not work. Also this does not work too:

IF  EXISTS(SELECT 1 FROM table1 WHERE col1 = ? LIMIT 1) BEGIN
DELETE FROM table2 WHERE col2 = ?
END

MySQL tell my there is a syntax error, How can I fix it?

like image 986
Shafizadeh Avatar asked Sep 28 '15 13:09

Shafizadeh


1 Answers

You can move the condition into the WHERE clause of DELETE to achieve the same effect, like this:

DELETE FROM table2
WHERE col2 = ?
  AND EXISTS(SELECT 1 FROM table1 WHERE col1 = ? LIMIT 1)

Note that the two ?s have switched places with relation to the original query.

like image 125
Sergey Kalinichenko Avatar answered Sep 20 '22 12:09

Sergey Kalinichenko