Autogenerate composite key in SQLite

烂漫一生 提交于 2019-12-11 13:50:56

问题


I have a composite primary key {shop_id, product_id} for SQLite Now, I want an auto-increment value for product_id which resets to 1 if shop id is changed. Basically, I want auto-generated composite key e.g.

Shop ID Product Id

1 1

1 2

1 3

2 1

2 2

3 1

Can I achieve this with auto-increment? How?


回答1:


Normal Sqlite tables are B*-trees that use a 64-bit integer as their key. This is called the rowid. When inserting a row, if a value is not explicitly given for this, one is generated. An INTEGER PRIMARY KEY column acts as an alias for this rowid. The AUTOINCREMENT keyword, which can only be used on said INTEGER PRIMARY KEY column, contrary to the name, merely alters how said rowid is calculated - if you leave out a value, one will be created whether that keyword is present or not, because it's really the rowid and must have a number. Details here. (rowid values are generally generated in increasing, but not necessarily sequential, order, and shouldn't be treated like a row number or anything like that, btw).

Any primary key other than a single INTEGER column is treated as a unique index, while the rowid remains the true primary key (Unless it's a WITHOUT ROWID table), and is not autogenerated. So, no, you can't (easily) do what you want.

I would probably work out a database design where you have a table of shops, a table of products, each with their own ids, and a junction table that establishes a many-to-many relation between the two. This keeps the product id the same between stores, which is probably going to be less confusing to people - I wouldn't expect the same item to have a different SKU in two different stores of the same chain, for instance.

Something like:

CREATE TABLE stores(store_id INTEGER PRIMARY KEY
                  , address TEXT
                    -- etc
                   );
CREATE TABLE product(prod_id INTEGER PRIMARY KEY
                   , name TEXT
                     -- etc
                   );
CREATE TABLE inventory(store_id INTEGER REFERENCES stores(store_id)
                     , prod_id INTEGER REFERENCES product(prod_id)
                     , PRIMARY KEY(store_id, prod_id)) WITHOUT ROWID;


来源:https://stackoverflow.com/questions/55332718/autogenerate-composite-key-in-sqlite

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