I have a table A and B, both look like this:
CREATE TABLE A (id integer CONSTRAINT aid PRIMARY KEY);
Now i want to model an optional one-to-many relation between A and B. Normally, I would extend the definition of B like so:
CREATE TABLE B (
id integer CONSTRAINT bid PRIMARY KEY,
a_id integer REFERENCES A(id)
);
but now a_id
can't be null
, so the relation isn't optional. So basically I want to be able to assign null
to this column, but if the value is not null then it must reference A.id
.
Yes, a_id
can be null in table B
. I tried it:
tmp=# CREATE TABLE A (id integer CONSTRAINT aid PRIMARY KEY);
CREATE TABLE
tmp=# CREATE TABLE B (
tmp(# id integer CONSTRAINT bid PRIMARY KEY,
tmp(# a_id integer REFERENCES A(id)
tmp(# );
CREATE TABLE
tmp=# insert into B (id,a_id) VALUES (3,null);
INSERT 0 1
tmp=#
Your current data model works.
您创建了另一个与A和B相关的表,该表仅包含“可选”关系
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.