このテーブルを想定すると:
CREATE TABLE students
(
student_id SERIAL PRIMARY KEY,
player_name TEXT
);
外部キーを定義する方法は4つあり(単一列PKを処理する場合)、それらはすべて同じ外部キー制約につながります。
-
ターゲット列に言及せずにインライン:
CREATE TABLE tests ( subject_id SERIAL, subject_name text, highestStudent_id integer REFERENCES students ); -
ターゲット列に言及するのと同じように:
CREATE TABLE tests ( subject_id SERIAL, subject_name text, highestStudent_id integer REFERENCES students (student_id) ); -
create table内の行外 :CREATE TABLE tests ( subject_id SERIAL, subject_name text, highestStudent_id integer, constraint fk_tests_students foreign key (highestStudent_id) REFERENCES students (student_id) ); -
別の
alter tableとして ステートメント:CREATE TABLE tests ( subject_id SERIAL, subject_name text, highestStudent_id integer ); alter table tests add constraint fk_tests_students foreign key (highestStudent_id) REFERENCES students (student_id);
どちらを好むかは好みの問題です。ただし、スクリプトには一貫性を持たせる必要があります。複数の列で構成されるPKを参照する外部キーがある場合は、最後の2つのステートメントが唯一のオプションです。この場合、FKを「インライン」で定義することはできません。 foreign key (a,b) references foo (x,y)
システムで生成されたPostgresからの名前が気に入らない場合は、バージョン3)と4)でのみFK制約の独自の名前を定義できます。
serial データ型は実際にはデータ型ではありません。これは、シーケンスから取得した列のデフォルト値を定義する簡単な表記です。したがって、参照する列 serialとして定義された列 適切な基本タイプintegerを使用して定義する必要があります (またはbigint bigserialの場合 列)