How to insert if not exists, or increase if exists

2020-05-09 02:17发布

问题:

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));

回答1:

You can use insert or replace.

I thinks this will do the trick

INSERT OR REPLACE INTO Test (Id,Val) 
  VALUES (  1,          
            COALESCE((SELECT Val + 1 FROM Test WHERE id = 1), 1)
          );
INSERT OR REPLACE INTO Test (Id,Val) 
  VALUES (  2,          
            COALESCE((SELECT Val + 1 FROM Test WHERE id = 2), 1)
          );

You just have to replace the numbers with your inputed id

Thanks Chico