2

我正在使用Postgres 9.6.2創建電影和電視節目流服務數據庫(用於學校項目)。我遇到了以下錯誤:PostgresSQL:僅引用複合主鍵的一部分的表

沒有唯一約束相匹配的引用表中給出鍵「watchedepisodes」

的TVratings見下表將採取一檔電視節目,只要用戶觀看在至少一集(顯示在WatchedEpisodes表中)並允許用戶對其進行評分。由於WatchedEpisodes具有用戶ID,電視節目ID,季節和劇集的複合主鍵,因此它不會讓我只從該表中引用僅包含uid和tid的組合鍵。

CREATE TABLE WatchedEpisodes (
    uid int unique references Users(uid), 
    tid int, 
    season int, 
    episode int, 
    FOREIGN KEY(tid, season, episode) REFERENCES Episodes(tid, season, episode), 
    PRIMARY KEY (uid, tid, season, episode) 
); 

CREATE TABLE TVRatings (
    uid int, 
    tid int, 
    rating int check (rating > 0 and rating < 6), 
    FOREIGN KEY(uid, tid) REFERENCES WatchedEpisodes(uid,tid), 
    PRIMARY KEY(uid, tid) 
); 

想知道是否有辦法只引用該組合鍵的一部分。這些只是我的兩張桌子,所以如果需要進一步的信息,我可以添加更多。

回答

-1

這實際上是在規範中,但它尚未實現。這就是所謂的MATCH PARTIAL

CREATE TABLE foo (
    a int, 
    b int, 
    c int, 
    PRIMARY KEY (a,b,c) 
); 
CREATE TABLE bar (
    a int, 
    b int, 
    FOREIGN KEY (a,b) REFERENCES foo (a,b) MATCH PARTIAL 
); 

您可以read about it in the docs

A value inserted into the referencing column(s) is matched against the values of the referenced table and referenced columns using the given match type. There are three match types: MATCH FULL, MATCH PARTIAL, and MATCH SIMPLE (which is the default). MATCH FULL will not allow one column of a multicolumn foreign key to be null unless all foreign key columns are null; if they are all null, the row is not required to have a match in the referenced table. MATCH SIMPLE allows any of the foreign key columns to be null; if any of them are null, the row is not required to have a match in the referenced table. MATCH PARTIAL is not yet implemented. (Of course, NOT NULL constraints can be applied to the referencing column(s) to prevent these cases from arising.)

我覺得目前它被視爲防功能,所以它不太可能很快隨時降落。

作爲一種變通方法,您可以創建只具有(a,b)

CREATE TABLE baz (
    a int, 
    b int, 
    PRIMARY KEY (a,b) 
); 

從這裏你可以兩個錶鏈接到它的另一個表...

CREATE TABLE foo (
    a int, 
    b int, 
    c int, 
    PRIMARY KEY (a,b,c), 
    FOREIGN KEY (a,b) REFERENCES baz 
); 
CREATE TABLE bar (
    a int, 
    b int, 
    FOREIGN KEY (a,b) REFERENCES baz 
); 
+0

你知道的另一種方式,我可以如果我不能做一個部分匹配,去解決這個問題? –

+0

@HannahRiedman更新。如果這個答案對您有用,請考慮將其標記爲已選,並將問題標記爲可能應該移至[dba.se]的問題。 ;) –

相關問題