0

次のビジネス ルールがあるとします。

  • ユーザーが 0 個以上のアカウントを持ち、すべてのアカウントが 1 人のユーザーに関連付けられている
  • ユーザーには 0 個以上のアセットがあり、すべてのアセットは 1 人のユーザーに関連付けられています
  • 資産は、単一のアカウントに関連付けることができます。アカウントに割り当てられている場合、そのアカウントはアセットに関連付けられたユーザーに属している必要があります。

次の提案されたスキーマを想定します。

User
-id

Account
-id
-user_id

Asset
-id
-user_id
-account_id (Nullable)

アセットは、そのアセットとは異なるユーザーに属するアカウントに割り当てられる可能性があるため、このスキーマには弱点があるようです。これは、より良いスキーマにつながる通常の形式の 1 つによって対処されていますか? 正規化によってカバーされていない場合は、ビジネスロジック側で最善の制約になりますか?

4

2 に答える 2

1

正規化が処理する可能性のあるこの(以下の)唯一の部分は、null許容列です。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);
于 2012-05-03T23:42:26.923 に答える
-1

テーブル Asset から account_id 外部キーを完全に削除することをお勧めします。account_id はユーザー テーブルに関連付けられているため、アセットとユーザーを結合してから、ユーザーからアカウントへの左結合を実行できます (これが account_id が主キーであるテーブルである場合)。左の結合から結果が得られた場合、アセットはアカウントにリンクされており、ユーザーは同じです。このようにして、その制約を強制します。

これが役に立てば幸いです、よろしく

エルチェ

于 2012-04-30T21:15:29.560 に答える