問題的部分原因是麥當勞和漢堡王都出售名爲「漢堡包」和「芝士漢堡」的產品和(我認爲)「雙層芝士漢堡」。因此,您在ProductLocation中存儲的信息不完整。
Product
--
Big Mac McDonald's
Hamburger McDonald's
Hamburger Burger King
ProductLocation
Big Mac McDonald's New York, building 1
Hamburger McDonald's New York, building 1
Hamburger Burger King Amsterdam, building 2
當他說「一個位置不僅僅是一棟建築物」時,duffymo說得對。
以下是實現這些約束的一種方法。我放棄了身份證號碼,因爲他們傾向於隱藏實際發生的事情。
create table company (
co_name varchar(15) primary key
);
insert into company values
('McDonald''s'),
('Burger King');
create table location (
loc_name varchar(30) primary key,
co_name varchar(15) not null references company (co_name),
unique (loc_name, co_name)
);
insert into location values
('New York, building 1', 'McDonald''s'),
('Amsterdam, building 2', 'Burger King');
create table product (
co_name varchar(15) not null references company (co_name),
product_name varchar(15) not null,
primary key (co_name, product_name)
);
insert into product values
('McDonald''s', 'Big Mac'),
('McDonald''s', 'Hamburger'),
('McDonald''s', 'Cheeseburger'),
('Burger King', 'Hamburger'),
('Burger King', 'Cheeseburger');
create table product_location (
loc_name varchar(30) not null references location (loc_name),
co_name varchar(15) not null,
product_name varchar(15) not null,
foreign key (co_name, product_name) references product (co_name, product_name),
foreign key (loc_name, co_name) references location (loc_name, co_name),
primary key (loc_name, co_name, product_name)
);
insert into product_location values
('Amsterdam, building 2', 'Burger King', 'Cheeseburger');
注意product_location中的重疊外鍵。重疊外鍵保證公司確定的位置和產品所屬的公司是同一家公司。現在下面的INSERT將會失敗並且違反外鍵約束。
insert into product_location values
('Amsterdam, building 2', 'McDonald''s', 'Cheeseburger');
「當我們向產品添加也是位置依賴的關係時,情況會變得更糟。如果他們也是公司依賴的話,那將更加棘手。 XYZ Burgers可能會賄賂一名沙特阿拉伯官員並有權在旅遊景點銷售BLT。 :-) – 2011-05-25 10:12:17