Why can't you use SQLite ROWID as a Primary key?

心不动则不痛 提交于 2019-12-03 16:34:33

问题


This does not execute:

create table TestTable (name text, age integer, primary key (ROWID))

The error message is:

11-23 11:05:05.298: ERROR/Database(31335): Failure 1 (table TestTable has no column named ROWID) on 0x2ab378 when preparing 'create table TestTable (name text, age integer, primary key (ROWID))'.

However, after the TestTable is created, this prepares and executes just fine:

create table TestTable (name text, age integer);

insert into TestTable (name, age) values ('Styler', 27);

select * from TestTable where ROWID=1;

I could potentially see ROWID as being a solution to needing an auto-increment primary key and foreign key which are never going to be used as populated as data on the application layer. Since ROWID is hidden from select result sets by default, it would have been nice to associate this with the primary key while keeping it hidden from the application logic. OracleBlog: ROWNUM and ROWID say this is impossible and inadvisable, but doesn't provide much explanation other than that.

So, since the answer to 'is this possible' is definitely no/inadvisable, the question is more or less 'why not'?


回答1:


Summary from SQLite.org:

In SQLite, table rows normally have a 64-bit signed integer ROWID which is unique among all rows in the same table. (WITHOUT ROWID tables are the exception.)

If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID. You can then access the ROWID using any of four different names, the original three names (ROWID, _ROWID_, or OID) or the name given to the INTEGER PRIMARY KEY column. All these names are aliases for one another and work equally well in any context.

Just use it as the primary key.



来源:https://stackoverflow.com/questions/8246649/why-cant-you-use-sqlite-rowid-as-a-primary-key

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