简体   繁体   中英

SQLite composite key (2 foreign keys) Link table

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 ?

NB 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.

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM