如何在sqlite中使用外键?

时间:2014-01-23 15:19:37

标签: android sqlite foreign-keys android-sqlite

我在sqlite中有两个表,它们与id“连接”。使用此表的应用程序在Android OS上运行。

表1;:

|id| entry 1| entry2|
|1 | aaaaaa | aaaaa |
|2 | bbbbbb | bbbbb |

表2:

|id| entryx| constant|
|1 | aaaaa | aaaaaaaa|
|1 | baaaa | baaaaaaa|
|1 | caaaa | caaaaaaa|
|2 | ababa | baabaaba|

目前,我使用循环删除具有以下查询的条目:

do{
    db.delete("Table 1","id='"+cid+"'",null);
    db.delete("Table 2","id='"+cid+"'",null);
  }
while(getNextID());

我想使用外键,它允许我删除表1中的条目,并且表2中的所有条目也被删除。此外,我必须考虑表2中的数据在插入表2之前插入。如何使用外键来执行此操作?该表使用id作为int,它是主键,第二个表使用相同的。

1 个答案:

答案 0 :(得分:5)

正如selvin建议在删除级联上使用

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

表1

CREATE TABLE table1 (
  id PRIMARY KEY  
 ,entry1 text,entry2 text
);

然后

insert into table1 values(1,"aaaa","aaaaa");
insert into table1 values(2,"bbbb","bbbbb");

表2

CREATE TABLE table2(
  id int references table1(id) ON DELETE CASCADE, entryx text, constant text
);


insert into table2 values(1,"aaaa","aaaaa");
insert into table2 values(1," baaaa ","baaaaaaa");
insert into table2 values(1,"  caaaa ","caaaaaaa")
insert into table2 values(2,"bbbb","bbbbb"); 

参赛后的表格

sqlite> select * from table1;
id          entry1      entry2    
----------  ----------  ----------
1           aaaa        aaaaa     
2           bbbb        bbbbb     
sqlite> select * from table2;
id          entryx      constant  
----------  ----------  ----------
1           aaaa        aaaaa      
1           baaaa       baaaaaaa  
1           caaaa       caaaaaaa  
2           bbbb        bbbbb  

删除

sqlite> delete from table1 where id=1;

删除后的表

sqlite> select * from table2;
id          entryx      constant  
----------  ----------  ----------
2           bbbb        bbbbb     


sqlite> select * from table1;
id          entry1      entry2    
----------  ----------  ----------
2           bbbb        bbbbb