I'm using SQLite to maintain a database which contains, among other things, a table with paths. The CREA开发者_如何转开发TE statement for the table looks like this
CREATE TABLE path (id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
UNIQUE(name));
I'm looking for a short way to say 'insert this given path into the path table and give me the id it was assigned, or just give me the id in case it existed already' in SQL.
Right now, I'm doing this with multiple SQL statements (pseudocode ahead):
unsigned int getIdForPath(p) {
result = exec("SELECT id FROM path WHERE name='$p';");
if result.empty {
exec("INSERT INTO path VALUES(NULL, '$p');");
result = exec("SELECT last_insert_rowid() FROM path;");
}
return result.toInt();
}
So, I'm first trying to look up the id; if it doesn't seem to exist, I add a new entry and finally do another SELECT to get the most recently used id. This seems a bit clumsy and possibly inefficient.
Is there any more compact and/or efficient way to implement this logic?
UPDATE: The common case is that the entry does exist already, so the initial SELECT in the above pseudo code will find a result in most of the cases.
You can do it with two steps by using INSERT OR IGNORE to insert the value if it does not already exist and than select id of the element.
精彩评论