SQLite composite key (2 foreign keys) Link table

Luke picture Luke · Nov 3, 2011 · Viewed 38.8k times · Source

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.

Answer

mu is too short picture mu is too short · Nov 4, 2011

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.