2011-09-02 125 views
1

說我有一個數據庫有多個權利,如person, company, conference,你必須跟蹤說addresses。我們可以爲同一個實體(人)提供多個地址。一種方法是爲每個實體分配一個單獨的地址表(person_address等)。另一種方法是擁有一個包含主鍵的地址表(Entity,id,address_type)。在這種方法中,我們不能使用地址表中的外鍵到實體。數據庫設計SQL Server

那麼有什麼更好的方法。有沒有另一種方法來做到這一點?

感謝

+2

at 2000 rep,你已經足夠長時間知道比標記一個問題'sql'和'server' –

回答

3

在邏輯建模POV中,您的描述強調了像person,company,conference等實體具有共同特徵的事實:它們具有零個,一個或多個地址。如果您將此類建模爲類層次結構,那麼您可能會創建一個Addressable類,並且會從此Addressable類繼承人員,公司和會議。您可以將相同的推理應用於您的數據模型,並將addresable表與addressable_entity_id配合使用。 person,company,conference實體將「繼承」此表。有三種設立方式實現表繼承:

所以你可以模擬你這樣的表:

create table Addresses (AddressId int not null identity(1,1) primary key, ...); 
create table Addressable (AddressableId int not null identity (1,1) primary key, ...); 
create table AddressableAddress (
    AddressId int not null, 
    AddressableId int not null, 
    constraint AddressableAddressAddressId 
     foreign key (AddressId) references Addresses(AddressId), 
    constraint AddressableAddressAddressableId 
     foreign key (AddressableId) references Addressable(AddressableId)); 
create table Person (PersonId int not null identity(1,1) primary key, 
    AddressableId int not null, 
    ..., 
    constraint PersonAddressableAddressableId 
     foreign key AddressableId references Addressable (AddressableId)); 
create table Company (CompanyId int not null identity(1,1) primary key, 
    AddressableId int not null, 
    ..., 
    constraint CompanyAddressableAddressableId 
     foreign key AddressableId references Addressable (AddressableId)); 

當然你必須找到絕對之間的平衡e關係正常形式和實際可用性。在這個方案中,我建議例如爲了插入一個新的人,必須先在Addressable中獲得一行,然後獲取AddressableId,然後繼續插入該人。這可能或可能也不起作用。順便說一句,有的方式在一個單獨的語句來完成這樣的插入使用OUTPUT子句鏈兩個插件:

insert into Addressable (AddressableType) 
output inserted.AddressableId, @FirstName, @LastName 
into Person (AddressableId, FirstName, LastName) 
values (AddressableTypePerson); 

但現在很難獲取新插入的PersonId

1

從技術上講,如果兩個人住在同一個地址,你不會是完全標準化的,如果根本就在TBLPerson行稱爲TBLAddress但是單一個一對多的詳細表,如果你只想每個物理地址一個實例,你將招致一個多對多關係表TBLPersonAddresses的開銷,其中FK的對TBLAddress

我會說,除非你希望在同一個地址的多個人是我的標準將TBLAddresspersonID列作爲01的詳細信息

編輯:我傾向於總是使用代理鍵,除非我有特別的理由不這樣做。