2011-11-03 76 views
13

我讀過相當清涼風格BNF語法指定SQLite create table語句SQLite的複合鍵(2個外鍵)鏈接表

這裏找到:http://www.sqlite.org/lang_createtable.html

我想知道我是怎麼想去創建這些之間的鏈接表

我有一個表,可以說,房子,和另一個electrical_items。

我想創建一個鏈接表,以將house_id和item_id作爲組合鍵,但我不確定我會如何去做,它似乎不允許主鍵是一個外鍵?

N.B我想要第三個字段pap_tested,它存儲了房屋中的電氣項目是pap_tested的日期,所以通過複合主鍵的這個鏈接表似乎是最好的方法。

回答

27

這些無論是應爲你的關聯表的工作:

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

你可能想separate (single column) indexes on house_items.house_id and house_items.item_id爲好。

+0

有跟着我並不認爲鏈接它適用的house_id是房屋的主鍵和物品的item_id。 – Luke

1

對於那些需要這種關係的設計,不存在對主鍵的禁止,也不是一個外鍵。但是,您的問題不是其中之一,因爲鏈接表中的自然PRIMARY KEY是兩列的組合,每個FOREIGN KEY都返回其他表中的一個。

+0

謝謝,我想我一定誤解了新的語法文法 – Luke

0

我使用兩個外鍵和更新級聯和刪除級聯選項創建一個表。

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

只是爲了補充第一個答案,這是一個很好的做法,一個名字添加到限制,如下面的代碼:

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