本(下同)實現關係正常化可能處理的是空列的唯一部分。在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);
「所有帳戶都與單個用戶相關聯」 - 這是否意味着沒有兩個用戶可以擁有相同的帳戶ID號? (對於資產也是同樣的問題。) –