简体   繁体   中英

How to get unique _id column for a multi-column primary key?

According to some blogs like http://reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ and even in some of the aswers here.

One of the first steps before including the datababe into the project is to rename the primary id field of your tables to "_id" so Android will know where to bind the id field of your tables.

What should be done with a table that have a combined primary key Assume that i'm creating the relation between the product id and the store id to assign it's price.

CREATE TABLE `Products-Stores` (
    `product`   INTEGER NOT NULL,
    `store` INTEGER NOT NULL,
    `price` INTEGER NOT NULL,
    PRIMARY KEY(product,store)
);

There is no need to rename any column in your database. SQL allows column aliases like this:

SELECT integer_primary_key AS _id 
   ...

The only time this is necessary is when you are using a ListAdapter to display the contents of a cursor queried from your DB. You must have an integer primary key column, named "_id" in the cursor, to do that

Better yet, every SQLite database table has an implicit column named "rowid". You don't even have to have your own integer primary key column. Just use rowid, like so:

SELECT rowid AS _id 
   ...

EDITED TO INCLUDE @CL's EXPLANATION OF WORKING JOINS

Obviously, this trick won't work, for many kinds of joins. As long as the rowids are unique over all the rows in the join, though, it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM