外键如何工作?

Joh*_*rum 5 database

我以前主要使用MyISAM表,它不支持外键.看看堆栈溢出,我没有找到一个很好的,简洁的解释外键实际上在做什么.我最感兴趣的是连接表,你会有这样的模式:

customers
id category_id

products
id category_id 

categories
id

customerproducts
customer_id product_id
Run Code Online (Sandbox Code Playgroud)

如果我在客户产品上有外键,它将确保只有有效的客户和只有有效的产品进入该表,但是如果我尝试将电话类别的产品添加到仅指定为对复印机感兴趣的客户?这会导致外键约束被违反吗?

Mik*_*ll' 1

我最感兴趣的是连接表,其中您将拥有如下所示的架构:

您不会有这样的模式——它不代表您感兴趣的事实。让我们用 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');
Run Code Online (Sandbox Code Playgroud)

产品有不同的类别。

create table categories (
  cat_name varchar(15) primary key
);
insert into categories values ('Cable'), ('Networking'), ('Phones');
Run Code Online (Sandbox Code Playgroud)

每个产品可能出现在多个类别中。

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');
Run Code Online (Sandbox Code Playgroud)

客户可能对多个类别的产品感兴趣。

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');
Run Code Online (Sandbox Code Playgroud)

如果我在客户产品上有外键,它将确保只有有效的客户和有效的产品才能进入该表,但是如果我尝试将电话类别中的产品添加到指定为仅对复印机感兴趣的客户,该怎么办?

客户并不是对他们喜欢的类别中的所有产品都感兴趣。请注意重叠的外键约束。

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');
Run Code Online (Sandbox Code Playgroud)

下一次插入将会失败,因为客户 1 对电话不感兴趣。

insert into product_interests values
(1, 152, 'Phones');
Run Code Online (Sandbox Code Playgroud)
错误:表“product_interests”的插入或更新违反了外键约束“product_interests_cust_id_fkey”
详细信息:表“customer_category_interests”中不存在键(cust_id,cat_name)=(1,电话)。