Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT if NOT EXISTS, But DELETE if it EXISTS

I have the following query to update a table record setting new foreignKey if that foreignKey and foreignKey2 did not already exist. This should work great, however, how can I modify to delete that particular pkID record if it DOES exist?

table structure:

+----------------+
| table          |
+----------------+
| pkID           |
| foreignKey     |
| foreignKey2    |
+----------------+

query:

UPDATE table a
SET a.foreignKey = 2
WHERE a.pkID = 1234
AND NOT EXISTS (
   SELECT 1
   FROM   table b
   WHERE  b.foreignKey = 2
   AND  b.foreignKey2 = a.foreignKey2
)
like image 679
NeilMPatterson Avatar asked Dec 09 '25 15:12

NeilMPatterson


1 Answers

You can delete if it exists, and only insert (instead of update since the record doesn't exist to be deleted) otherwise. But it is not clear what the 3rd value should be.

DELETE tbl where pkID = 1234;
if @@ROWCOUNT = 0
    INSERT tbl(foreignKey, pkID, foreignKey2)
    VALUES (2, 1234, ??)
like image 103
RichardTheKiwi Avatar answered Dec 11 '25 04:12

RichardTheKiwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!