1

I have a single table ("#detail" in example below) that will have a child relationship to one of three tables (always one table and no others). For example, #detail rows 'aaaa' and 'bbbb' need a column value that relates to #metainfo1,row1 and row 'cccc' needs to be related to #metainfo2.row1 and 'dddd' needs to be related to #metainfo3,row1.

I would rather not create a new column in #detail for every #metainfo table, because I will have to add new #detail columns as new #metainfo tables are added during the lifetime of the database, and every row in #detail will have at least 2 null values (and more null columns as #metainfo grows).

I thought about creating a junction/join table to sit in between #detail and the #metainfo tables, but that just seems to move the excessive null columns and expansion work to another table (and adds additional IO).

Can anyone recommend a way to make this multiple parent relationship work?

Thanks.

create table #detail (detailid int identity(1,1) primary key , detailinfo varchar(4) )
create table #metainfo1 (meta1id int primary key )
create table #metainfo2 (meta2id int primary key)
create table #metainfo3 (meta3id int primary key)
insert into #detail 
   select 'aaaa' union select 'bbbb' union select 'cccc' union select 'dddd'
insert into #metainfo1 
   select 1 
insert into #metainfo2
   select 1 
insert into #metainfo3
   select 1 
4

1 回答 1

1

我建议对您的数据进行规范化,以便将元信息合并到一个表中。我们一起放一张图:

MetaInfotypes (parent) --1-to-many--> MetaInfo (child)
MetaInfo (parent) --1-to-many--> Detail (child)

这意味着:一个或多个细节将与元信息相关。一个或多个 MetaInfo 将与一个类型相关。

让我们看一下表结构:

-- Example: MetaInfo1, MetaInfo2, MetaInfo3
create table MetaInfoTypes (
  id int identity(1, 1) primary key, 
  name varchar(20), 
  constraint uk_MetaInfoTypes_name unique(name)
);

create table MetaInfo (
  id int identity(1,1) primary key,  
  MetaInfotypeid int,
  somevalue varchar(100),
  foreign key (MetaInfotypeid) references MetaInfoTypes(id)
);

create table detail (
  detailid int identity(1,1) primary key, 
  detailinfo varchar(4),
  MetaInfoid int,
  foreign key (MetaInfoid) references MetaInfo(id)
);

用虚拟数据查看这个SQLFiddle

这样您就不必添加 MetaInfo 表。您只需将数据推送到 MetaInfo 表中并限定 MetaInfo 的类型。为了轻松添加类型,我们有 MetaInfoTypes 表。然后只需将细节与选择的元信息相关联即可。

当必须添加新的元信息时,将其添加到 MetaInfoType。然后将数据添加到该类型的 MetaInfo。然后将数据添加到详细信息并引用 MetaInfo 的 Id。

于 2013-09-15T01:42:14.167 回答