How to guarantee uniqueness when N tables have 1:1 relationship with a common table?

拟墨画扇 提交于 2019-12-04 17:26:46

This may be what @Pranay meant, but the answer was incomplete. Add a column TYPE to all tables and then constrain it like this:

create table Animal (id integer, 
                     type string,
                     name string,
                     primary key (id),
                     unique (id, type)
                    );

create table Bird (id integer,
                   type string default 'BIRD' check (type='BIRD'),
                   primary key (id),
                   foreign key (id, type) references Animal (id, type)
                  );

create table Dog (id integer,
                  type string default 'DOG' check (type='DOG'),
                  primary key (id),
                  foreign key (id, type) references Animal (id, type)
                 );

See David Portas's blog fora good explanation of this.

In you databayse you can add one more column in you table like AnimalType

AnimalTable 
   Id
   AnimalType -- 1 = dog, 2= bird, 3= other

I don't think that this can be done without triggers / constraints whilst keeping the tables separate.

I feel that the database design here is wrong. The reason I say that is it seems that for every new animal you have to create new table. In general you want to create a database in the way so that every time you need to add data the schema does not change.

Here is one way to do it:
Table animals
animal_id PK
name

Table animailProperties
property_id PK
name

Table animalDecription
animail_id FK
property_id FK
property_data

Example:

Table animals
1 DOG
2 Cat
3 Bird

Table animailProperties
1 legs
2 wings
3 fly

Table animalDecription
1 1 4 (dog legs 4)
1 2 0 (dog wings 0)
1 3 0 (dog fly no)
2 1 4 (cat legs 4)
2 2 0 (cat wings 0)
2 3 0 (cat fly no)
3 1 2 (bird legs 2)
3 2 2 (bird wings 2)
3 3 1 (bird fly yes)

Something along these lines. So you can create any type of properties for every possible animal.
Every time you need to create a new animal, you just assign correct properties to it.

I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!