首页 文章

postgresql外键语法

提问于
浏览
96

我将在下面的posgresql代码中看到2个表 . 第一个表学生有2列,一个用于student_name,另一个student_id是主键 . 在我的第二个名为tests的表中,这有4列,一个用于subject_id,一个用于subject_name,然后一个用于在一个主题中具有最高分数的学生,即最高学生 . 我试图让highStudent_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中创建外键的正确方法是什么?

1 回答

  • 184

    假设这个表:

    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 "inline",例如 foreign key (a,b) references foo (x,y)

    只有版本3)和4)才能让你能够为FK约束定义你自己的名字,如果你不喜欢Postgres的系统生成的那个 .


    serial 数据类型实际上不是数据类型 . 它只是一个简写符号,用于定义从序列中获取的列的默认值 . 因此,必须使用适当的基本类型 integer (或 bigintbigserial 列)定义引用定义为 serial 的列的任何列 .

相关问题