Alternative to SQLite INSERT … ON CONFLICT … WHERE … DO UPDATE SET

我是研究僧i 提交于 2020-11-29 10:47:40

问题


I'm running an application that uses SQLite3 version 3.7.17 on Linux. It's erroring out on this statement:

INSERT INTO taxa (taxon_id, rank, parent_id) VALUES (?,?,?)
        ON CONFLICT (taxon_id) WHERE parent_id is NULL
        DO UPDATE SET parent_id=excluded.parent_id,rank=excluded.rank

But the same code runs on version 3.28.0. Is there another way of writing this statement so it can run on 3.7.17?


回答1:


ON CONFLICT... or UPSERT was added to SQLite in version 3.24.0.

In earlier versions you can get similar functionality with 2 separate statements.

First try to update the table:

UPDATE taxa 
SET rank = ?, parent_id = ?
WHERE taxon_id = ?;

If a row with the taxon_id = ? exists it will be updated.
If it does not exist nothing will happen.

Then try to insert the new row with INSERT OR IGNORE:

INSERT OR IGNORE INTO taxa (taxon_id, rank, parent_id) VALUES (?, ?, ?);

If a row with the taxon_id = ? exists nothing will happen (I assume that taxon_id is the PRIMARY KEY of the table or at least defined as UNIQUE).
If it does not exist then the new row will be inserted.



来源:https://stackoverflow.com/questions/62010726/alternative-to-sqlite-insert-on-conflict-where-do-update-set

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