简体   繁体   中英

SQL Query : IF exist delete ELSE update

Good Day,

Right now Im having a hard time figuring if is it possible to have an IF ELSE function inside an sql query. I want to DELETE a row with same location and name, then UPDATE if not exist.

      $sql = "IF EXISTS (SELECT * FROM location_tbl WHERE name = '$a' && location = 'Drawing Room')
                            DELETE FROM location_tbl WHERE name = '$a' 
                                ELSE
                                INSERT INTO location_tbl (id, name, datetime, location) VALUES ('', '$a' , NOW(),'Drawing Room')";

Thank you so much for your KIND HELP

You can have IF ELSE in the SELECT part of SQL, not in the way you want it.

You can do what you need in 2 SQLs - delete and then insert.

In Oracle you can use MERGE statement which can conditionally INSERT, UPDATE and DELETE. Please see https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606

I think using if-else is not necessary in your case. You can always delete the existing record first and then insert a new one. If the record does not exist in the table, the delete statement will not delete anything from the table.

One suggestion would be to run the if statement using php:

$result = $mysqli->query("SELECT * FROM location_tbl WHERE name = '".$a."' AND location = 'Drawing Room'"); 
if($result->num_rows > 0 ){
    $mysqli->query("DELETE FROM location_tbl WHERE name = '".$a."'");
} else {
    $mysqli->query("INSERT INTO location_tbl (id, name, datetime, location) VALUES ('', '".$a."' , NOW(),'Drawing Room')");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM