【发布时间】:2010-09-25 16:39:08
【问题描述】:
我有一个名为“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 的最高效方法是什么。
【问题讨论】: