Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

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.

like image 641
Luke Avatar asked Nov 03 '11 22:11

Luke


1 Answers

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.

like image 143
mu is too short Avatar answered Oct 06 '22 05:10

mu is too short