postgresql-create带有不相交子类的表

mzmfm0qo  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(271)

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

对于所有行通用的列(id、common1、common2),它显然非常简单(如下面的代码所示)。

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

--<what to put here???>

);

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

cczfrluj

cczfrluj1#

postgres表继承的工作方式如下:

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

如果要使用symphony列,必须查询symphony。

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

试试看
更传统的结构将使用如下连接表:

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

试试看

相关问题