1

I have the following database in Android:

Table A: [_id, value1]
Table B: [_id, fk_tablea, value2]

With code:

db.execSQL("CREATE TABLE IF NOT EXISTS table_A ( "
        + "_id long primary key , value1 long  );");
db.execSQL("CREATE TABLE IF NOT EXISTS table_B ( "
        + "_id long primary key ,fk_tablea long  , value2 long,"
        + "FOREIGN KEY (fk_tablea) REFERENCES table_A (value1) ON DELETE CASCADE);");

And if I make (with the table empty):

ContentValues values= new ContentValues();
values.put("_id",1);
values.put("value1",900);
mDb.replace("table_A", null, values);

or

mDb.execSQL("INSERT OR REPLACE  INTO table_A(_id,value1) VALUES (1,900)");

of

mDb.insertWithOnConflict("table_A", null, values, SQLiteDatabase.CONFLICT_REPLACE);

It crashes with an exception Caused by: android.database.sqlite.SQLiteException: foreign key mismatch: , while compiling: INSERT OR REPLACE INTO table_A(_id,value1) VALUES (2,900) . But if instead of replace I use insert

ContentValues values= new ContentValues();
values.put("_id",1);
values.put("value1",900);
mDb.insert("table_A", null, values);

Works correctly, why is that happening? and how can I solve it? Thanks in advance

Addev
  • 31,819
  • 51
  • 183
  • 302
  • see [Similar Question](http://stackoverflow.com/questions/5208245/what-is-causing-foreign-key-mismatch-error) – Shehzad Apr 13 '12 at 17:29

1 Answers1

3

The foreign key in table_B refers to a non-unique field value1 in table_A. The following demonstrates how that cannot work:

sqlite> pragma foreign_keys=1;
sqlite> create table foo (a int, b int);
sqlite> create table bar (c int, d int, foreign key (c) references foo(b));
sqlite> insert into foo values (1,1);
sqlite> insert into bar values (1,1);
Error: foreign key mismatch
sqlite> create unique index idx1 on foo(b);
sqlite> insert into bar values (1,1);
sqlite> 

Documentation this way:

http://www.sqlite.org/foreignkeys.html#fk_indexes