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

后端 未结 1 1250
感动是毒
感动是毒 2021-01-29 03:45

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 t

1条回答
  •  伪装坚强ぢ
    2021-01-29 04:36

    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

    0 讨论(0)
提交回复
热议问题