私はほとんど興味は、あなたがこのようなスキーマを持つことになり、テーブル、参加:
をあなたはそのようなスキーマを持っていないだろう - それは事実にあなたを表すものではありません」に興味があります。SQLでいくつかのテーブルをスケッチしましょう。 (PostgreSQLでテスト済み)まず、顧客と製品。
-- Customer names aren't unique.
create table customers (
cust_id integer primary key,
cust_name varchar(15) not null
);
insert into customers values (1, 'Foo'), (2, 'Bar');
-- Product names are unique.
create table products (
prod_id integer primary key,
prod_name varchar(15) not null unique
);
insert into products values
(150, 'Product 1'), (151, 'Product 2'), (152, 'Product 3');
商品にはさまざまなカテゴリがあります。
create table categories (
cat_name varchar(15) primary key
);
insert into categories values ('Cable'), ('Networking'), ('Phones');
各製品はいくつかのカテゴリに表示されることがあります。
create table product_categories (
prod_id integer not null references products,
cat_name varchar(15) not null references categories,
primary key (prod_id, cat_name)
);
insert into product_categories values
(150, 'Cable'), (150, 'Networking'), (151, 'Networking'), (152, 'Phones');
お客様は、いくつかの製品カテゴリに興味があるかもしれません。私はcustomerproductsに外部キーを持っている場合は
create table customer_category_interests (
cust_id integer not null references customers,
cat_name varchar(15) not null references categories,
primary key (cust_id, cat_name)
);
-- Nobody's interested in phones
insert into customer_category_interests values
(1, 'Cable'), (1, 'Networking'), (2, 'Networking');
、それだけで 有効な顧客および唯一の有効な製品は、そのテーブルに入ることを保証しますが、私はに電話カテゴリから製品を追加しようとした場合はどうでしょう 顧客 コピー機にのみ興味があるものとして指定されていますか?
お客様はの製品をお好きなカテゴリに登録することができます。重複する外部キーの制約に注意してください。
create table product_interests (
cust_id integer not null,
prod_id integer not null,
cat_name varchar(15) not null,
foreign key (cust_id, cat_name) references customer_category_interests,
foreign key (prod_id, cat_name) references product_categories,
primary key (cust_id, prod_id, cat_name)
);
insert into product_interests values
(1, 150, 'Cable'), (2, 150, 'Networking');
カスタマー1は電話機に興味がないので、この次の挿入は失敗します。
insert into product_interests values
(1, 152, 'Phones');
ERROR: insert or update on table "product_interests" violates foreign key constraint "product_interests_cust_id_fkey"
DETAIL: Key (cust_id, cat_name)=(1, Phones) is not present in table "customer_category_interests".
重複の可能性:http://stackoverflow.com/questions/4262554/database-design-whats-the-point-of-identifying-foreign-keys、http://stackoverflow.com/質問/ 18717/are-foreign-keys-really-in-database-design、http://stackoverflow.com/questions/83147/whats-wrong-with-foreign-keys – LittleBobbyTables
これら3つの質問はすべて本質的に何故?どうやって尋ねようとしているの?素晴らしいハンドルbtw。 –