外键列中的 NULL

Gna*_*fly 8 postgresql foreign-key

我一直在学习SIMPLEFULL匹配 PostgreSQL 中的外键,我想知道以下思考过程是否正确:

一旦外键的至少一个引用列包含一个NULL值,就没有指向被引用表的链接。这是因为根据 3VL,aNULL无法与另一个NULL值进行比较。这也意味着在相关列中至少包含一个值的引用行被更新或删除时,定义的级联操作(例如... DO DELETE, ... DO SET NULL, ..)NULL永远不会发生,因为没有指向引用行的链接。更具体地说,假设有一个从表A(x, y)到的外键B(x, y)。如果同时AB包含的行(5, NULL)xy,有没有联系,因为NULL该行A是不是等于NULL在列B

这样对吗?我对 SQL 很陌生,所以我想知道我是否正确理解了这一点。

Len*_*art 7

你太对了。我在Fiddle创建了一个小例子

create table p
( a int not null
, b int
, unique (a,b)
);

create table c
( a int not null
, b int
, constraint fk_p foreign key (a,b)
                  references p (a,b)
                      on delete cascade
                      on update cascade
);

-- insert data in parent:
insert into p (a,b) values (1,null);  -- ok
insert into p (a,b) values (1,null);  -- also ok. The constraint evaluates to null,
                                      -- which is ok. The rule is that it must not 
                                      -- evaluate to false

-- insert data in child
insert into c (a,b) values (1,null);  -- ok
insert into c (a,b) values (2,null);  -- also ok, foreign key evaluates to null. 
                                      -- So despite there is no 2 in
                                      -- parent this is ok

-- remove data from parent
delete from p;

-- all rows present in child
select * from c;

a   b
1   null
2   null 
Run Code Online (Sandbox Code Playgroud)

Null 使即使是微不足道的事情也有点难以掌握。我不会推荐包含空值的候选键。