How to insert if not exists, or increase if exists in SQLite?

夙愿已清 提交于 2019-12-02 21:36:37

问题


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



来源:https://stackoverflow.com/questions/17823170/how-to-insert-if-not-exists-or-increase-if-exists-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!