5 mysql sql-server oracle postgresql database-design
例如,给定3个表:
并假设我们要执行
设置架构以实施这些约束的最佳方法是什么?
我为postgres提供了一个可能的答案,我对postgres和Oracle的解决方案特别感兴趣,但也有兴趣查看其他RDBMS的解决方案
编辑
作为参考,以下答案/评论中的SO问题解决了类似的问题:
小智 3
我自己的 postgres 解决方案(但我不知道这是否是最好的方法):
枚举:
create type gastropod_type as enum ('slug', 'snail');
Run Code Online (Sandbox Code Playgroud)
表和约束:
create table gastropod(
gastropod_id serial unique,
gastropod_type gastropod_type,
slug_gastropod_id integer,
snail_gastropod_id integer,
average_length numeric,
primary key(gastropod_id, gastropod_type),
check( (case when slug_gastropod_id is null then 0 else 1 end)+
(case when snail_gastropod_id is null then 0 else 1 end)=1) );
create table slug(
gastropod_id integer unique,
gastropod_type gastropod_type check (gastropod_type='slug'),
is_mantle_visible boolean,
primary key(gastropod_id, gastropod_type),
foreign key(gastropod_id, gastropod_type)
references gastropod deferrable initially deferred );
create table snail(
gastropod_id integer unique,
gastropod_type gastropod_type check (gastropod_type='snail'),
average_shell_volume numeric,
primary key(gastropod_id, gastropod_type),
foreign key(gastropod_id, gastropod_type)
references gastropod deferrable initially deferred );
alter table gastropod
add foreign key(slug_gastropod_id, gastropod_type)
references slug deferrable initially deferred;
alter table gastropod
add foreign key(snail_gastropod_id, gastropod_type)
references snail deferrable initially deferred;
Run Code Online (Sandbox Code Playgroud)
测试:
insert into gastropod(gastropod_type, slug_gastropod_id, average_length)
values ('slug', currval('gastropod_gastropod_id_seq'), 100);
insert into slug(gastropod_id, gastropod_type, is_mantle_visible)
values (currval('gastropod_gastropod_id_seq'), 'slug', true);
select gastropod_id, gastropod_type, average_length, is_mantle_visible
from gastropod left outer join slug using(gastropod_id, gastropod_type)
left outer join snail using(gastropod_id, gastropod_type);
gastropod_id | gastropod_type | average_length | is_mantle_visible
--------------+----------------+----------------+-------------------
1 | slug | 100 | t
(1 row)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2559 次 |
| 最近记录: |