简体   繁体   中英

Does an IF NOT EXISTS mySQL query exist?

just doing an INSERT using mySQL which works fine...

 mysql_query("INSERT INTO FLIGHTS_AVAILABLE 
 (aircraftID, aircraftType, maxSeats) VALUES('$theaircraftID', '$addType', '$maxCapacity'      ) ") 
or die(mysql_error());  

 echo '<p>';
 echo "The following details were added into the database:";
 echo "<hr>";

  echo $theaircraftID . $addType . $maxCapacity;

This works fine, however I've looked online and whilst I have heard of a feature called IF NOT EXISTS, there are not very good explanations online about it's use.

Is there anyway, I can run this query above, providing that if for example $theaircraftID = 10, and there is already a row in the database where the aircraftID = 10, then the query would not be run?

Thanks for any help you may be able to suggest,

Tom

Add a UNIQUE INDEX on 'FLIGHTS_AVAILABLE'.'aircraftID' . MySQL will block additional INSERT s with the same value. Additionally you can use ON DUPLICATE KEY EXISTS to run an UPDATE incase the INSERT give a DUPLICATE KEY constraint error.

您可以尝试按必需列创建唯一索引,然后使用INSERT IGNOREmysql_affected_rows

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