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 do not know why the above request does not work. Also this does not work either:

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

MySQL will tell me that there is a syntax error, how can I fix it?

+5
source share
1 answer

You can move the condition to the WHERE DELETE WHERE to achieve the same effect as this:

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

Please note that two ? switch places relative to the original request.

+8
source

Source: https://habr.com/ru/post/1232455/


All Articles