简体   繁体   English

是否存在IF不存在mySQL查询?

[英]Does an IF NOT EXISTS mySQL query exist?

just doing an INSERT using mySQL which works fine... 只是使用mySQL进行INSERT工作正常...

 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. 这工作正常,但我已经在线查看,虽然我听说过一个名为IF NOT EXISTS的功能,但在网上对它的使用并没有很好的解释。

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? 无论如何,我可以在上面运行这个查询,假设如果例如$ theaircraftID = 10,并且数据库中已经有一行,其中aircraftID = 10,那么查询将不会运行?

Thanks for any help you may be able to suggest, 感谢您提供的任何帮助,

Tom 汤姆

Add a UNIQUE INDEX on 'FLIGHTS_AVAILABLE'.'aircraftID' . 'FLIGHTS_AVAILABLE'.'aircraftID'上添加UNIQUE INDEX 'FLIGHTS_AVAILABLE'.'aircraftID' MySQL will block additional INSERT s with the same value. MySQL将阻止具有相同值的其他INSERT Additionally you can use ON DUPLICATE KEY EXISTS to run an UPDATE incase the INSERT give a DUPLICATE KEY constraint error. 此外,您可以使用ON DUPLICATE KEY EXISTS运行UPDATEINSERT会发出DUPLICATE KEY约束错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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