我有一个名为“images”的表:
CREATE TABLE images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
caption TEXT
);
在插入一行时,我希望 URL 列是唯一的。同时,我想找出具有该 URL 的行的 ID。
INSERT OR IGNORE images (url, caption) VALUES ("http://stackoverflow.com", "A logo");
SELECT last_insert_rowid(); -- returns the id iff there was an insert.
当然,我想尽快完成,尽管我的第一个想法是遵循以下伪代码:
int oldID = execSQL("SELECT last_insert_rowid()");
execSQL("INSERT OR IGNORE images (url, caption) VALUES ('http://stackoverflow.com', 'A logo')");
int newID = execSQL("SELECT last_insert_rowid()");
if (newID != oldID) {
// there was an insert.
return newID;
} else {
// we'd already seen this URL before
return execSQL("SELECT id FROM images WHERE url = 'http://stackoverflow.com'");
}
但这看起来效率极低。
从 INSERT OR IGNORE 语句获取自动递增行 ID 的最高效方法是什么。
最佳答案
在 Android 2.2 中,您可以使用 SQLiteDatabse.insertWithOnConflict
。 Link.
Returns the row ID of the newly inserted row OR the primary key of the existing row if the input param 'conflictAlgorithm' = CONFLICT_IGNORE OR -1 if any errorOR -1 if any error
在旧版本的 SDK 中,您可以:
- 查询条目是否存在
- 如果找到条目 - 返回所选项目的 id
- 如果没有找到 - 使用
SQLiteDatabse.insert
插入条目(它将返回新项目的主键)。
如果需要,还可以考虑使用事务。
关于sql - 从 SQLite 中的 INSERT OR IGNORE 语句中查找自动递增的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3794579/