我在聯接表最感興趣,在這裏你將有一個這樣的模式:
你不會有這樣的一個模式 - 它並不代表事實你」重新感興趣。讓我們在SQL中概述一些表。 (在PostgreSQL中測試)首先,客戶和產品。
-- Customer names aren't unique.
create table customers (
cust_id integer primary key,
cust_name varchar(15) not null
);
insert into customers values (1, 'Foo'), (2, 'Bar');
-- Product names are unique.
create table products (
prod_id integer primary key,
prod_name varchar(15) not null unique
);
insert into products values
(150, 'Product 1'), (151, 'Product 2'), (152, 'Product 3');
有不同的產品類別。
create table categories (
cat_name varchar(15) primary key
);
insert into categories values ('Cable'), ('Networking'), ('Phones');
每個產品可能出現在幾個類別中。
create table product_categories (
prod_id integer not null references products,
cat_name varchar(15) not null references categories,
primary key (prod_id, cat_name)
);
insert into product_categories values
(150, 'Cable'), (150, 'Networking'), (151, 'Networking'), (152, 'Phones');
客戶可能會對幾類產品感興趣。
create table customer_category_interests (
cust_id integer not null references customers,
cat_name varchar(15) not null references categories,
primary key (cust_id, cat_name)
);
-- Nobody's interested in phones
insert into customer_category_interests values
(1, 'Cable'), (1, 'Networking'), (2, 'Networking');
如果我有customerproducts外鍵,這將確保只有 有效客戶,唯一有效的產品進入該表,但什麼 ,如果我試圖從手機類別添加產品一位專門指定爲僅對複印機有興趣的客戶 ?
顧客對沒有興趣產品在他們偏好的類別。請注意重疊的外鍵約束。
create table product_interests (
cust_id integer not null,
prod_id integer not null,
cat_name varchar(15) not null,
foreign key (cust_id, cat_name) references customer_category_interests,
foreign key (prod_id, cat_name) references product_categories,
primary key (cust_id, prod_id, cat_name)
);
insert into product_interests values
(1, 150, 'Cable'), (2, 150, 'Networking');
這下一個插入將失敗,因爲客戶1對電話不感興趣。
insert into product_interests values
(1, 152, 'Phones');
ERROR: insert or update on table "product_interests" violates foreign key constraint "product_interests_cust_id_fkey"
DETAIL: Key (cust_id, cat_name)=(1, Phones) is not present in table "customer_category_interests".
可能的重複:http://stackoverflow.com/questions/4262554/database-design-whats-the-point-of-identifying-foreign-keys,http://stackoverflow.com/問題/ 18717 /是 - 外鍵 - 真正必要的數據庫設計,http://stackoverflow.com/questions/83147/whats-wrong-with-foreign-keys – LittleBobbyTables 2012-07-19 13:56:46
所有這三個問題是主要是問爲什麼?我想問怎麼樣?真棒處理順便說一句。 – 2012-07-19 14:34:15