I'm repeating two main points from previous answers I think you should keep:
Don't (try to) use "on duplicate key update" since its MySQL-only, as txyoji points out.
Prefer the select->if
not found then insert->else
insert demonstrated by Uday Sawant.
There's another point here, though: Concurrency. Although for low traffic applications the probability that you'll get in trouble is minimal (still never zero), I think we always be careful about this.
From a transactional point of view, "INSERT .. ON DUPLICATE UPDATE"
is not equivalent to selecting into your application's memory and then inserting or updating. The first is a single transaction, then second is not.
Here's a bad scenario:
- You do select your record using
findByPk()
which returns null
- Some other transaction (from some other user request) inserts a record with the id you just failed to select
- At the next instant you try to insert it again
In this case you'll either get an exception (if you're working with a unique key, as you do here) or a duplicate entry. Duplicate entries are much harder to pick up (usually nothing seems weird until your users see duplicate records).
The solution here is to set a strict isolation level, for example "serializable", and then begin a transaction.
Here's an example for yii:
Yii::app()->db->createCommand('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE');
$trn = Yii::app()->db->beginTransaction();
try {
// Try to load model with available id i.e. unique key
// Since we're in serializable isolation level, even if
// the record does not exist the RDBMS will lock this key
// so nobody can insert it until you commit.
// The same shold for the (most usual) case of findByAttributes()
$model = someModel::model()->findByAttributes(array(
'sapce_id' => $sapceId,
'day' => $day
));
//now check if the model is null
if (!$model) {
$model = new someModel();
}
//Apply you new changes
$model->attributes = $attributes;
//save
$model->save();
// Commit changes
$trn->commit();
} catch (Exception $e) {
// Rollback transaction
$trn->rollback();
echo $e->getMessage();
}
You can see more about isolation levels at least in the following links and see what every isolation level has to offer in data integrity in exchange for concurrency
http://technet.microsoft.com/en-us/library/ms173763.aspx
http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html