sql >> Databasteknik >  >> RDS >> SQLite

Hur använder man en främmande nyckel i sqlite?

Som selvin föreslog användning på radera kaskad

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

Tabell 1

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

Sedan

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

Tabell 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"); 

Tabeller efter inmatning

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  

Ta bort

sqlite> delete from table1 where id=1;

Tabeller efter borttagning

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


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



  1. Kontrollera om ett objekt är en primärnyckel med OBJECTPROPERTY() i SQL Server

  2. Skanningar av allokeringsorder

  3. SQL Union – En omfattande guide om UNION-operatören

  4. Ställer du in främmande nycklar i phpMyAdmin?