【问题标题】:Postgresql - create table with disjoint subclassesPostgresql - 创建具有不相交子类的表
【发布时间】:2020-10-23 17:25:33
【问题描述】:

我不确定如何在 postgresql 上创建具有不相交子类的表。我在下面的 ER 图中表示了(非常简化的版本)我的问题,显示了两个子类和每个子类的属性。

对于所有行共有的列(id、common1、common2),显然很简单(如下代码所示)。

create table Music (
    id          serial,
    common1 int not null, 
    common2 boolean not null, 

--<what to put here???>

);

但是我不确定考虑子类问题的最佳方式。有谁知道从这里去哪里?

【问题讨论】:

  • layers、at1、lead、strings及其值代表什么?
  • 我认为this thread 可以帮助你。
  • @Schwern Symphony 的列是 id、common1、common2、layers 和 at1。协奏曲的列是 id、common1、common2、lead 和 strings。我想知道这是否可以在一个名为 Music 的表中考虑。
  • @CarlosBazilio 浏览了这个,但只包含对我不想购买的书籍的引用

标签: sql postgresql


【解决方案1】:

Postgres table inheritance 会这样工作:

create table music (
    id serial primary key,
    common1 int not null, 
    common2 boolean not null
);

create table symphony (
    layers int not null,
    at1 text not null
) inherits(music);

create table concerto (
    lead text not null,
    strings integer not null
) inherits(music);

考虑我们是否在每个表中都有一行。

insert into concerto (common1, common2, lead, strings)
  values (1, true, 'a', 5);
insert into symphony (common1, common2, layers, at1)
  values (2, false, 3, 'b');
insert into music (common1, common2)
  values (3, true);

它们都是一排排的音乐。

-- Fetches id, common1, and common2 from all rows.
select *
from music

如果您只想查询音乐中的行,请指定only music

-- Fetches id, common1, and common2 from only the one row in music.
select *
from only music

如果你想使用交响乐列,你必须查询交响乐。

-- Fetches id, common1, common2, layers, at1 only from symphony
select *
from symphony

Try it


更传统的结构会像这样使用连接表:

create table music (
    id serial primary key,
    common1 int not null, 
    common2 boolean not null
);

create table music_symphony (
    music_id integer references music(id),
    layers int not null,
    at1 text not null
);

create table music_concerto (
    music_id integer references music(id),
    lead text not null,
    strings integer not null
);

insert into music (id, common1, common2)
  values (1, 1, true);
insert into music_concerto(lead, strings)
  values ('a', 5);

insert into music (id, common1, common2)
  values (2, 2, false);
insert into music_symphony (music_id, layers, at1)
  values (2, 3, 'b');
  
insert into music (id, common1, common2)
  values (3, 3, true);

-- Fetch all symphonies
select *
from music m
join music_symphony ms on ms.music_id = m.id

Try it

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多