SQLite composite key (2 foreign keys) Link table

拜拜、爱过 提交于 2020-01-10 08:49:08

问题


I've read the rather cool styled BNF grammar for the SQLite create table statement

found here: http://www.sqlite.org/lang_createtable.html

I was wondering how I'd go about creating a link table between these

I have one table, lets say, houses, and another electrical_items.

I want to create a link table to have the house_id and the item_id as a composite key, but I'm not sure how I'd go about doing it, it doesn't appear to allow a primary key to be a foreign key ?

N.B I want a third field pap_tested which stores the date the electrical item in the house was pap_tested so this linking table via composite primary key seems the best approach.


回答1:


Either of these should work for your association table:

create table house_items (
    house_id integer not null,
    item_id  integer not null,
    foreign key (house_id) references houses(id),
    foreign key (item_id) references electrical_items(id),
    primary key (house_id, item_id)
)

create table house_items (
    house_id integer not null references houses(id),
    item_id  integer not null references electrical_items(id),
    primary key (house_id, item_id)
)

You'll probably want separate (single column) indexes on house_items.house_id and house_items.item_id as well.




回答2:


Just to complement the first answer, it's a good practice to add a name to constraints, like the code below:

create table house_items (
    house_id integer not null,
    item_id  integer not null,
    constraint house_items_pk primary key (house_id, item_id),
    constraint house_items_house_fk foreign key (house_id) references houses(id),
    constraint house_items_items_fk foreign key (item_id) references electrical_items(id));



回答3:


There is no prohibition about a PRIMARY KEY not also being a FOREIGN KEY for those designs that require this kind of relation. Your problem isn't one of those, however, since the natural PRIMARY KEY in the linking table is a composite of the two columns, each a FOREIGN KEY back to one of the other tables.




回答4:


I create a table with two foreign keys and options of on update cascade and on delete cascade.

CREATE TABLE category_subcategory
(
 category_subcategory_id INTEGER PRIMARY KEY,
 category_id             INTEGER NOT NULL,
 subcategory_id          INTEGER NOT NULL,
 FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE ON
 UPDATE CASCADE,
 FOREIGN KEY(subcategory_id) REFERENCES subcategories(subcategory_id) ON
 DELETE CASCADE ON UPDATE CASCADE
 );


来源:https://stackoverflow.com/questions/8002756/sqlite-composite-key-2-foreign-keys-link-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!