简体   繁体   中英

Is it possible to create a nullable foreign key constraint in PostgreSQL?

I have a nullable int8 column 'z_id' on a table 'XY'. The 'z_id' is the primary key of the 'Z' table. I'd like to have a constraint that maps the 'Z' entity to the 'XY' table if the 'z_id' is provided during persistense.

If I understand you correctly, you try to:

t=# create table z(i int primary key);
CREATE TABLE
t=# insert into z values (1);
INSERT 0 1
t=# create table xy(i int);
CREATE TABLE
t=# insert into xy values(1),(null);
INSERT 0 2
t=# alter table xy add constraint fk foreign key (i) references z(i);
ALTER TABLE
t=# select * from xy;
 i
---
 1

(2 rows)

And you probably had same doubdts ?..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM