SQLite “INSERT OR REPLACE INTO” vs. “UPDATE … WHERE”

后端 未结 4 1933
暖寄归人
暖寄归人 2020-11-29 22:24

I\'ve never seen the syntax INSERT OR REPLACE INTO names (id, name) VALUES (1, \"John\") used in SQL before, and I was wondering why it\'s better than UPD

4条回答
  •  眼角桃花
    2020-11-29 22:33

    REPLACE INTO table(column_list) VALUES(value_list);
    

    is a shorter form of

    INSERT OR REPLACE INTO table(column_list) VALUES(value_list);
    

    For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.

    REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.


    This is a work around.. not checked the speed..

    INSERT OR IGNORE INTO table (column_list) VALUES(value_list);
    

    followed by

    UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'
    

    This method allows a replace to occur without causing a trigger.

提交回复
热议问题