简体   繁体   中英

SQL insert only if

i am trying to insert the new data if and only if, this data doesnot exist in the database, if it exists, just break the insert operation and take the next item and try to check and insertg again, i want something like this:

insert into db if field_id doesnot exist, if exist, dont touch anything, neither update nor anything

ON DUPLICATE KEY UPDATE is not what i want and INSERT IGNORE seems to be mysterious to me now

this is my attempt:

$check = "SELECT anzeige_id FROM table WHERE anzeige_id = '$whatIhaveInMyHand'";
$checked=mysql_query($check);
if(mysql_num_rows($checked)==0){
$sql = "INSERT INTO table (`firmen_id`,`anzeige_id`,`anzeige_txt`) VALUES ('$firma_id','$anzeigen_id','$anzeige_txt')";
$sql_inserted = mysql_query($sql);
if($sql_inserted){
   echo "inserted into db <br/>";
}else{
  echo "anzeige_id already exists ".$anzeigen_id."<br/>";
}

what is good for my plan?

您必须先阅读,然后插入,或者您必须信任INSERT IGNORE ,这将有效地忽略插入会导致 UNIQUE/PRIMARY 键违规的任何行。

Set a UNIQUE constraint on the field you are using to identify the data set if it is not already PRIMARY KEY and use INSERT IGNORE. That will result in new data set being inserted and old data sets failing to insert silently.

Set a counter and read all the records:

if(counter>0) {
   record available
}

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