最近在写sqilte语句更新数据时发现个问题,那就是Replace into执行时居然会把id主键修改了。google了一下,原来Replace的原理是找到待修改的记录后,整条删除,然后插入新记录。所以这个过程中,默认的id主键会被修改。有时候这种结果并不是我们所想要的,应该如何解决呢?
http://stackoverflow.com/questions/2717590/sqlite-upsert-on-duplicate-key-update这里有很好的讨论。
个人觉得以下方法最好,摘抄如下。
INSERT OR REPLACE INTO page (id, name, title, content, author)
SELECT old.id, new.name, new.title, old.content, new.author
FROM ( SELECT
"about" AS name,
"About this site" AS title,
42 AS author
) AS new
LEFT JOIN (
SELECT id, name, content
FROM page WHERE name= "about"
) AS old ON new.name = old.name;