I have the following table:
CREATE TABLE 'Test' ('Id' INTEGER PRIMARY KEY NOT NULL, 'Val' INTEGER)
If a given Id doesn't exist, I want to insert the Id with a default Val. But if it already exists, I want to increase the value of Val.
I have this code:
$data = array(':id'=>$id);
$stmt = $db->prepare('INSERT INTO Test (Id, Val) Values(:id, 1);');
if(!$stmt->execute($data)){
$stmt = $db->prepare('UPDATE Test SET Val=Val+1 WHERE Id=:id');
$stmt->execute($data);
}
and it works, but I would want to do it with a single SQL statement. Can I?
EDIT:
From @Xikinho90's answer, my final code is
$stmt = $db->prepare('
INSERT OR REPLACE INTO Test (Id,Val)
VALUES ( :id, COALESCE((SELECT Val + 1 FROM Test WHERE id = :id), 1) )
');
$stmt->execute(array(':id'=>$id));