规范化可能处理的唯一部分(如下)是可为空的列。在 Chris Date 的理解中,如果一个列允许 NULL,那么关系就不是 1NF。
如果你试图严格遵循关系模型,我认为你会用断言来处理这个问题。但是大多数 SQL 平台不支持断言。在 SQL 中,我相信您正在寻找类似的东西。我在 PostgreSQL 中对此进行了测试。
create table users (
user_id integer primary key
);
create table accounts (
user_id integer not null references users (user_id),
account_id integer not null unique,
primary key (user_id, account_id)
);
create table assets (
user_id integer not null references users (user_id),
asset_id integer not null unique,
account_id integer null,
primary key (user_id, asset_id),
foreign key (user_id, account_id) references accounts (user_id, account_id)
);
-- Insert 3 users.
insert into users values (1), (2), (3);
-- User 1 has two accounts, user 2 has 3 accounts, user 3 has none.
insert into accounts values
(1, 100),
(1, 101),
(2, 102),
(2, 103),
(2, 104);
-- User 1 has 1 asset not assocated with an account.
insert into assets values (1, 200, null);
-- User 1 has 1 asset associated with account 101
insert into assets values (1, 201, 101);
-- User 1 tries to associate an asset with account 102, which doesn't belong to user 1.
insert into assets values (1, 202, 102);
[Fails with foreign key violation]
-- User 2 has two assets not associated with an account.
insert into assets values
(2, 500, null),
(2, 501, null);