开发者

Problem with inserting into android sqlite3 table that has composite primary key

I have a table with a composite primary key and I am having trouble inserting. The code used to create the table is:

CREATE TABLE ClassEvent (
    EventName varchar(10) NOT NULL, 
    CourseId varchar(10) NOT NULL, 
    EventType varchar(20), 
    EventWeight number(3), 
    DueDate DATE NOT NULL, 
    FOREIGN KEY (CourseId) REFERENCES Courses(CourseId), 
    PRIMARY KEY (CourseId, EventName));

The problem I am havi开发者_如何学Cng is when I want to insert records that have values that may not be unique for the columns CourseId or EventName, but are a unique combination of the 2. for example, if I try to run the following 2 inserts:

INSERT INTO ClassEvent VALUES('Assignment 1','60-415','Assignment',10,'12/10/2010');
INSERT INTO ClassEvent VALUES('Project 1','60-415','Project',15,'5/12/2010');

I get the following error:

Error: columns CourseId, EventName are not unique.

and the second insert does not make it into the DB. Why does this error out? I thought that a composite primary key requires that the combination of both values are unique. In my above inserts, the values for the EventName column are different even though the values for CourseId are the same. Shouldn't this be seen as 2 unique combinations and thus 2 different primary keys?

My table needs to be able to hold several different events for each CourseId, but each Event must be unique for each Course. I need to be able to insert values into the table like:

EventName CourseId Assignment 1 60-415 Project 1 60-415 Assignment2 60-415 Project 2 60-415 Assignment 1 60-367 Project 1 60-367

and so on. Can anyone tell me how I can get this to work? Why are these composite PK's not being seen as unique entries? Any help would be much appreciated.


Here is the java function I am using for the insert:

public void addNewClassEvent(ContentValues values) {
    SQLiteDatabase db = openConnection();

    db.insert("ClassEvent", null, values);
    db.close();
}

Could this be causing the problem?


You can have a composite primary key in SQLite, but you have to create the key when you create the table:

   CREATE TABLE example1(
      field1 FLOAT,
      field2 TEXT,
      PRIMARY KEY(field1, field2)
   );

You cannot create the primary key after the fact using ALTER TABLE.

On the other hand, you can create a UNIQUE INDEX after the fact which has essentially the same effect as a PRIMARY KEY:

   CREATE UNIQUE INDEX pk_index ON "table1"("field1","field2");

I am not sure how you have created, the tables, and if you have added the primary index later, but grab the database to your desktop, and check out how works in a desktop environment.


You can't make combinations like that, but you don't need them. What is stopping you from just having a truly id column ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜