2

私はPostgres 9.6.2を使用して、映画やテレビ番組のストリーミングサービスデータベース(学校プロジェクト用)を作成しています。私は、次のようなエラーに実行しています:PostgresSQL:複合主キーの一部のみを参照するテーブル

参照表「watchedepisodes」に指定されたキーに一致するユニーク制約

は、以下のTVratingsテーブルは限り利用者がで見たように、テレビ番組を取るはありません少なくとも1つのエピソード(これは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) 
); 

複合キーの一部のみを参照する方法があるかどうかわかりません。これらは私のテーブルの2つだけなので、さらに情報が必要な場合は、さらに追加することができます。

答えて

-1

これは実際の仕様ですが、まだ実装されていません。それは、あなたが、私は現在、それは抗機能として見たので、それはいつでもすぐに上陸する可能性はないと思う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.)

をすることができます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 
); 

と呼ばれています。

回避策として、あなたはちょうどあなたがそれに両方のテーブルをリンクすることができますここから(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]に移してください。 ;) –

関連する問題