markdown 用Postgres编写外键的不同方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 用Postgres编写外键的不同方法相关的知识,希望对你有一定的参考价值。

[stackoverflow](https://stackoverflow.com/a/28560619/3821430)

Assuming this table:

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

There are four different ways to define a foreign key (when dealing with a single column PK) and they all lead to the same foreign key constraint:

1. Inline without mentioning the target column:

```
CREATE TABLE tests 
( 
   subject_id SERIAL,
   subject_name text,
   highestStudent_id integer REFERENCES students
);
```

2. Inline with mentioning the target column:
```
CREATE TABLE tests 
( 
   subject_id SERIAL,
   subject_name text,
   highestStudent_id integer REFERENCES students (student_id)
);
```

3. Out of line inside the create table:
```
CREATE TABLE tests 
( 
  subject_id SERIAL,
  subject_name text,
  highestStudent_id integer, 
  constraint fk_tests_students
     foreign key (highestStudent) 
     REFERENCES students (student_id)
);
```

4.As a separate alter table statement:
```
CREATE TABLE tests 
( 
  subject_id SERIAL,
  subject_name text,
  highestStudent_id integer
);

alter table tests 
    add constraint fk_tests_students
    foreign key (highestStudent) 
    REFERENCES students (student_id);
```
Which one you prefer is a matter of taste. But you should be consistent in your scripts. The last two statements are the only option if you have foreign keys referencing a PK that consists of more than one column - you can't define the FK "inline" in that case, e.g. foreign key (a,b) references foo (x,y)

Only version 3) and 4) will give you the ability to define your own name for the FK constraint if you don't like the system generated ones from Postgres.

以上是关于markdown 用Postgres编写外键的不同方法的主要内容,如果未能解决你的问题,请参考以下文章

外键和主键的 Postgres 和索引

用不同的值替换也用作外键的主键

如何在 prisma 中使用带有外键的 createMany?

如何选择引用同一列作为外键的所有(表,列)

请问SQL server 中的主键和外键的作用

使用 SequelizeJS 编写带有外键的迁移