codememo

PostgreSQL 외부 키 구문

tipmemo 2023. 5. 23. 21:55
반응형

PostgreSQL 외부 키 구문

제 포스그레에 보시는 것처럼 테이블이 두 개 있습니다.아래 SQL 코드입니다.첫 번째 테이블 학생들은 두 개의 열을 가지고 있습니다, 하나는 다음을 위한 것입니다.student_name그리고 또 한 명.student_id기본 키입니다.

테스트라고 불리는 제 두 번째 테이블에는 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))

Postgre에서 외부 키를 만드는 올바른 방법은 무엇입니까?SQL 부탁합니다.

이 표를 가정하면:

CREATE TABLE students 
( 
  student_id SERIAL PRIMARY KEY,
  player_name TEXT
);

단일 열 PK를 처리할 때 외부 키를 정의하는 네 가지 방법이 있으며, 모두 동일한 외부 키 제약 조건으로 이어집니다.

  1. 대상 열을 언급하지 않고 인라인:

    CREATE TABLE tests 
    ( 
       subject_id SERIAL,
       subject_name text,
       highestStudent_id integer REFERENCES students
    );
    
  2. 대상 열을 언급하는 것과 일치:

    CREATE TABLE tests 
    ( 
       subject_id SERIAL,
       subject_name text,
       highestStudent_id integer REFERENCES students (student_id)
    );
    
  3. 내부의 라인을 벗어남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)
    );
    
  4. 별도로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)

버전 3)과 4)만 Postgres에서 생성된 시스템 이름이 마음에 들지 않으면 FK 제약 조건에 대한 사용자 이름을 정의할 수 있습니다.


serial데이터 유형이 실제 데이터 유형이 아닙니다.시퀀스에서 가져온 열의 기본값을 정의하는 간단한 표기법입니다.따라서 열을 참조하는 열은 다음과 같이 정의됩니다.serial적절한 기본 유형을 사용하여 정의해야 합니다.integer(또는)bigint위해서bigserial열)

ALTER TABLE table_name ADD FOREIGN KEY(colunm_name) REFERENCES reference_table_name(reference_column_name);

열이 이미 생성되어 있어야 합니다.

언급URL : https://stackoverflow.com/questions/28558920/postgresql-foreign-key-syntax

반응형