아래 posgresql 코드에서 볼 수 있듯이 2 개의 테이블이 있습니다. 첫 번째 테이블 students에는 2 개의 열이 있습니다. 하나는 student_name 용이고 다른 하나는 기본 키인 student_id입니다. 내 두 번째 테이블 테스트에서 이것은 subject_id에 대한 하나, subject_name에 대한 하나, 그리고 가장 높은 과목에서 가장 높은 점수를 가진 학생에 대한 하나, 가장 높은 Student_id 인 4 개의 열을 가지고 있습니다. highStudent_id가 내 students 테이블의 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
열)