2012-07-19 72 views
5

我以前主要使用過MyISAM表,它們不支持外鍵。看看堆棧溢出問題,我沒有找到關於外鍵實際上在做什麼的簡明扼要的解釋。我在聯接表最感興趣,在這裏你將有一個這樣的模式:外鍵如何工作?

customers 
id category_id 

products 
id category_id 

categories 
id 

customerproducts 
customer_id product_id 

如果我有customerproducts外鍵,這將確保只有合法的用戶,只有有效的產品進入該表,但如果我嘗試將電話類別中的產品添加到指定爲僅對複印機有興趣的客戶,那麼該如何處理?這是否會導致違反外鍵約束?

+0

可能的重複: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

+0

所有這三個問題是主要是問爲什麼?我想問怎麼樣?真棒處理順便說一句。 – 2012-07-19 14:34:15

回答

1

我在聯接表最感興趣,在這裏你將有一個這樣的模式:

你不會有這樣的一個模式 - 它並不代表事實你」重新感興趣。讓我們在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".