问题的部分原因是麦当劳和汉堡王都出售名为“汉堡包”和“芝士汉堡”的产品和(我认为)“双层芝士汉堡”。因此,您在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