人员和组织是超类型/子类型关系中事物的一个很好的例子。它们并不相同,但也不是完全不同的。他们有许多共同的属性。个人和组织都有地址和电话号码,个人和组织都可以是诉讼中的原告和被告,个人和组织显然都可以在您的系统中拥有 cmets。
要在 SQL dbms 中实现这一点,请将人和组织共有的列放在一个名为“Parties”的表中。人们独有的列放在人员表中;组织特有的列进入组织表。使用每个子类型一个视图来隐藏实现细节;您的客户使用视图,而不是表格。
您将使用超类型表“Parties”中的密钥作为 cmets 的所有者。 (我认为。)
这是一个简化的示例。
create table parties (
party_id integer not null unique,
party_type char(1) not null check (party_type in ('I', 'O')),
party_name varchar(10) not null unique,
primary key (party_id, party_type)
);
insert into parties values (1,'I', 'Mike');
insert into parties values (2,'I', 'Sherry');
insert into parties values (3,'O', 'Vandelay');
-- For "persons", a Subtype of "parties"
create table pers (
party_id integer not null unique,
party_type char(1) not null default 'I' check (party_type = 'I'),
height_inches integer not null check (height_inches between 24 and 108),
primary key (party_id),
foreign key (party_id, party_type) references parties (party_id, party_type)
);
insert into pers values (1, 'I', 72);
insert into pers values (2, 'I', 60);
-- For "organizations", a subtype of "parties"
create table org (
party_id integer not null unique,
party_type CHAR(1) not null default 'O' check (party_type = 'O'),
ein CHAR(10), -- In US, federal Employer Identification Number
primary key (party_id),
foreign key (party_id, party_type) references parties (party_id, party_type)
);
insert into org values (3, 'O', '00-0000000');
create view people as
select t1.party_id, t1.party_name, t2.height_inches
from parties t1
inner join pers t2 on (t1.party_id = t2.party_id);
create view organizations as
select t1.party_id, t1.party_name, t2.ein
from parties t1
inner join org t2 on (t1.party_id = t2.party_id);
使用您的 dbms 提供的任何功能使视图可更新。 (可能会触发。)然后应用程序代码可以插入到适当的视图中。