[英]PostgreSQL Foreign Key syntax
我有 2 個表,您將在下面的 PosgreSQL 代碼中看到。 第一個表 students 有 2 列,一個是student_name
,另一個是student_id
,它是主鍵。
在我的第二個名為 tests 的表中,它有 4 列,一列用於subject_id
,一列用於subject_name
,然后一列用於科目中得分最高的學生highestStudent_id
。 我試圖讓highestStudent_id
參考我的學生表中的student_id
。 這是我下面的代碼,不確定語法是否正確:
CREATE TABLE students ( student_id SERIAL PRIMARY KEY,
player_name TEXT);
CREATE TABLE tests ( subject_id SERIAL,
subject_name,
highestStudent_id SERIAL REFERENCES students);
語法highestStudent_id SERIAL REFERENCES students
是否正確? 因為我見過另一個像highestStudent_id REFERENCES students(student_id))
請問在 PostgreSQL 中創建外鍵的正確方法是什么?
假設這張表:
CREATE TABLE students
(
student_id SERIAL PRIMARY KEY,
player_name TEXT
);
定義外鍵有四種不同的方法(在處理單列 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,則最后兩個語句是唯一的選擇 - 在這種情況下,您不能定義 FK“內聯”,例如foreign key (a,b) references foo (x,y)
如果您不喜歡系統從 Postgres 生成的名稱,只有版本 3) 和 4) 可以讓您為 FK 約束定義自己的名稱。
serial
數據類型並不是真正的數據類型。 它只是一個簡寫符號,它定義了從序列中獲取的列的默認值。 因此,任何引用定義為serial
的列的列都必須使用適當的基本類型integer
(或bigint
用於bigserial
列)來定義
ALTER TABLE table_name ADD FOREIGN KEY(colunm_name) REFERENCES reference_table_name(reference_column_name);
請注意,該列必須已經創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.