如何在Android上的SQLite数据库中实现"继承"关系

Avi*_*ron 9 sqlite schema inheritance android database-design

考虑这个简单的模型:

基本位置表:

+-------------------------------+
|           Locations           |
+-------------------------------+
|(PK) _id Integer Autoincrement |
|     name Text(100) Not null   |
|     is_in_range Integer       |
+-------------------------------+
Run Code Online (Sandbox Code Playgroud)

更专业的表叫做WifiLocation:

+-------------------------------+
|         wifi_location         |
+-------------------------------+
|     ssid Text(0) Not null     |
|     signal_threshold Real     |
|(PK) _id Integer               |
+-------------------------------+
Run Code Online (Sandbox Code Playgroud)

我希望这个模型代表一个WifiLocation继承自BaseLocation.所以我在表REFERENCES_id列上添加了一个子句,如下wifi_locations所示:

CREATE TABLE wifi_locations (_id Integer primary key references Locations(_id), ....)
Run Code Online (Sandbox Code Playgroud)

我试图在这些表之间建立1:1的关系.

当我想向wifi_locations表中插入一行时,我首先将适当的值(Name,IsInRange)插入Locations表中,然后返回rowId.然后我将其余的数据(ssid)wifi_locations与rowId一起作为外键插入到表中.

所以插入到Location表是有效的,我正在返回一个Id,但是当我尝试使用这个Id并将其插入到wifi_locations表时,我收到了一个SQL Constraint violation错误.关于究竟出了什么问题没有更多细节.

我的架构有什么问题吗?有没有更好的方法来实现这种建模?

编辑:

确切的错误:

06-16 15:56:42.846: E/Database(2038):
android.database.sqlite.SQLiteConstraintException: 
error code 19: constraint failed
Run Code Online (Sandbox Code Playgroud)

Sim*_*iak 5

您应该在“位置”表FOREIGN KEY中将引用的第二个表中创建PRIMARY KEY。在SQLite FOREIGN KEYS中受支持,但隐式未启用,因此首先必须启用它们。

final String ENABLE_FOREIGN_KEYS ="PRAGMA foreign_keys=ON";
db.execSQL(ENABLE_FOREIGN_KEYS);
Run Code Online (Sandbox Code Playgroud)

用你的onOpen()方法SQLiteOpenHelper

然后,您的FOREIGN KEY外观如下所示:

CREATE TABLE wifi_location (
   SSID TEXT NOT NULL,
   SIGNAL_THRESHOLD REAL,
   _id INTEGER,  
  FOREIGN KEY(_id) REFERENCES Locations(_id)
);
Run Code Online (Sandbox Code Playgroud)

因此,但这一切都自此生效SQLite version 3.6.19。有关更多信息,请参见SQLite外键支持