从
mysql页:
The main idea is to insert records using the ignore statement. If
you use the IGNORE keyword, errors that occur while executing the
INSERT statement are treated as warnings instead. For example, without
IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY
value in the table causes a duplicate-key error and the statement is
aborted. With IGNORE, the row still is not inserted, but no error is
issued. Then retrieve the last ID using mysql_insert_id
如果记录不存在,它将被插入并返回最后一个ID.
现在,如果没有记录返回,可以进行选择.这意味着一条记录已经存在,所以只需使用它.
例:
// make sure $id is safe (preventing sql injections)
$sql = "INSERT IGNORE INTO yourtable SET `field1` = 'value1' ... ";
mysql_query($sql);
if(mysql_affected_rows() == 1) { // no record found and then the inserts worked
$id = mysql_insert_id(); // id from the primary key
// add to cache
}
else {
// you can also cache them when they were inserted (faster to run than a select statement)
$id = retreiveFromCache($field1, $field2 /* etc...*/);
if(!$id) { // no record found in cache
// now the select can be done using the fields received
// make sure your use the right index otherwise it can be slow
$sql = "SELECT id FROM promotions_referrals WHERE `field1` = 'value1' ... "; //
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$id = $row['id'];
// add to cache
}
}
在这一点上,您将有$id分配,您确定没有重复/ mysql错误.
注意:如果域属于一个客户端,请使用客户端标识,而不是使用域.这样,您将使用INT作为比VARCHAR快的索引.相同的推荐代码.