2013-10-03 60 views
1

我正在構建一個包含2個模板的站點:統計數據和標籤,但它們之間也有一個N:M映射。在PostgreSQL中不可能映射兩個兄弟表之間的映射表?

統計信息和標籤在網站上都有自己的頁面,並且這些頁面具有共同的特徵,所以我想要一個名爲pages的父表。

create table pages (id serial primary key, title varchar(50)); 
create table stats (show_average boolean) inherits (pages); 
create table tags (color varchar(50)) inherits (pages); 
create table stat_tags (
    stat_id int 
    ,tag_id int 
    ,foreign key (stat_id) references stats(id) 
    ,foreign key (tag_id) references tags(id) 
); 

這最後詢問產量:

ERROR: there is no unique constraint matching given keys for referenced table "tags" 

如果我這樣做,沒有繼承這樣的:

create table stats (id serial primary key, title varchar(50), show_average boolean); 
create table tags (id serial primary key, title varchar(50), color varchar(50)); 
create table stat_tags (
    stat_id int 
    ,tag_id int 
    ,foreign key (stat_id) references stats(id) 
    ,foreign key (tag_id) references tags(id) 
); 

...它接受所有查詢。

PostgreSQL中可能有兩個孩子有映射表嗎?怎麼樣?

謝謝!

回答

1

使用inherits可能不是執行此操作的最佳方法。

繼承特性的一個嚴重的侷限性是索引 (包括唯一約束)和外鍵約束只適用 單表,而不是他們的子女繼承。 在外鍵約束的引用和引用方都是如此。

Caveats

我會更舒服東西沿着這些路線。

create table pages (
    id serial primary key, 
    page_type char(1) not null 
    check (page_type in ('s', 't')), 
    title varchar(50) not null unique, 
    unique (id, page_type) 
); 

create table stats (
    id integer primary key, 
    page_type char(1) not null default 's' 
    check(page_type = 's'), 
    show_average boolean, 
    foreign key (id, page_type) references pages (id, page_type) 
); 

create table tags (
    id integer primary key, 
    page_type char(1) not null default 't' 
    check(page_type = 't'), 
    color varchar(50) not null 
); 

create table stat_tags (
    stat_id int not null, 
    tag_id int not null, 
    primary key (stat_id, tag_id), 
    foreign key (stat_id) references stats(id), 
    foreign key (tag_id) references tags(id) 
); 

在生產中,你可能要建兩個更新視圖,一個解決網頁和統計數據之間的連接,以及一個解決頁面和標籤之間的連接。

+0

工作,謝謝! – user4681

+0

就這樣,我們通過upvoting好答案和接受正確答案表示感謝。 –