Question

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 
Était-ce utile?

La solution

I would recommend normalization of your data so that metainfo are merged into a single table. Let's put an diagram together:

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

This means: One or more detail will be related to a MetaInfo. One or more MetaInfo will be related to a Type.

Let's look at the table structures:

-- 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)
);

Check out this SQLFiddle with dummy data

This way you won't have to add MetaInfo tables. You would just push the data into MetaInfo table and just qualify the type of MetaInfo. To add types easily, we have MetaInfoTypes table. Then simply associate a detail with the meta info of choice and you are done.

When a new meta info has to be added, add it to the MetaInfoType. Then add data to MetaInfo for that type. Then add data to detail and reference MetaInfo's Id.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top