2015-01-09 3 views
0

Предположим, что у меня есть таблица продуктов, которые я продаю своим клиентам.Нормализация общей базы данных

Каждая запись имеет идентификатор продукта и имя продукта.

Я могу продать более 1 продукта каждому клиенту, но я хочу разрешить клиентам заказывать определенные продукты.

Как выглядят эти таблицы?

Это то, что я до сих пор:

PRODUCTS 
+------------+-------------+ 
| PROD_ID | PROD_NAME | 
+------------+-------------+ 

CUSTOMER 
+------------+-------------+ 
| CUST_ID | CUST_NAME | 
+------------+-------------+ 

ORDERS 
+------------+-------------+ 
| ORDER_ID | CUST_ID | 
+------------+-------------+ 
+5

Когда вы говорите, что вы хотите, чтобы клиенты только иметь возможность заказать определенные продукты, как будет это ограничение будет исполнено? – JRLambert

+1

вам нужна таблица соединения customer_product для определения продуктов, которые заказчик может заказать. – radar

+2

Как насчет 'CUST_ID' в' ORDERS', а затем добавить новую таблицу с именем 'CUSTOMER_PRODUCTS' с' CUST_ID' и 'PROD_ID' для допустимых продуктов для клиентов. – Edper

ответ

1

я написал и проверил это с PostgreSQL, но принципы одинаковы для любой СУБД SQL.

Таблицы для продуктов и клиентов просты.

create table products (
    prod_id integer primary key, 
    prod_name varchar(35) not null 
); 
insert into products values 
(1, 'Product one'), (2, 'Product two'), (3, 'Product three'); 

create table customers (
    cust_id integer primary key, 
    cust_name varchar(35) not null 
); 
insert into customers values 
(100, 'Customer 100'), (200, 'Customer 200'), (300, 'Customer 300'); 

Таблица «allowed_products» контролирует, какие продукты каждый клиент может заказать.

create table permitted_products (
    cust_id integer not null references customers (cust_id), 
    prod_id integer not null references products (prod_id), 
    primary key (cust_id, prod_id) 
); 
insert into permitted_products values 
-- Cust 100 permitted to buy all three products 
(100, 1), (100, 2), (100, 3), 
-- Cust 200 permitted to buy only product 2. 
(200, 2); 

У Заказчика 300 нет разрешенных продуктов.

create table orders (
    ord_id integer primary key, 
    cust_id integer not null references customers (cust_id) 
); 
insert into orders values 
(1, 100), (2, 200), (3, 100); 

В таблице «order_line_items» находится «волшебство». Ограничение внешнего ключа на {cust_id, prod_id} предотвращает заказы продуктов без разрешений.

create table order_line_items (
    ord_id integer not null, 
    line_item integer not null check (line_item > 0), 
    cust_id integer not null, 
    prod_id integer not null, 
    foreign key (ord_id) references orders (ord_id), 
    foreign key (cust_id, prod_id) references permitted_products (cust_id, prod_id), 
    primary key (ord_id, line_item) 
); 

insert into order_line_items values 
(1, 1, 100, 1), (1, 2, 100, 2), (1, 3, 100, 3); 
insert into order_line_items values 
(2, 1, 200, 2); 
insert into order_line_items values 
(3, 1, 100, 3); 

Оформить заказ клиента 300 можно. , ,

insert into orders values (4, 300); 

. , , но вы не можете вставлять какие-либо позиции.

insert into order_line_items values (4, 1, 300, 1); 
 
ERROR: insert or update on table "order_line_items" violates foreign key constraint "order_line_items_cust_id_fkey" 
DETAIL: Key (cust_id, prod_id)=(300, 1) is not present in table "permitted_products". 
Смежные вопросы