MySQL 不使用外來鍵約束的實操(二)

2021-09-05 03:36:07 字數 2924 閱讀 6806

網際網路開發中不用外來鍵到底是個什麼意思?

都說網際網路開發盡量不用外來鍵,那麼這裡的不用外來鍵到底代表的啥意思呢?

1. 這裡有一層意思很明確:

不用外來鍵約束。比如刪除一張表中的資料時,如果要級聯刪除另一張表中關聯的資料,以往是由資料庫來級聯約束的,現在應該將其移到程式中由程式來保持資料的一致性。

2. 另外一層意思:

外來鍵的定義就是在乙個表中的字段是另外一張表中的主鍵。如果僅按照"不使用外來鍵"這幾個字的字面理解,就是要把外來鍵字段抽取出來放在一張中間表中。簡單說就是都當成多對多來處理。

比如:

使用者(userid,username)  訂單(orderid,totalprice,userid)
問題1:這裡useid就是乙個外來鍵,如果不用外來鍵,是否就要設計成這樣?

使用者(userid,username)  訂單(orderid,totalprice)使用者-訂單中間表(userid,orderid)
問題2:如果是這樣,假如一張表有多個外來鍵,豈不是要有很多中間表?

都說網際網路開發盡量不用外來鍵,那麼這裡的不用外來鍵到底代表的啥意思呢?

這裡的外鍵指的資料庫的外來鍵約束。

不用外來鍵約束。比如刪除一張表中的資料時,如果要級聯刪除另一張表中關聯的資料,以往是由資料庫來級聯約束的,現在應該將其移到程式中由程式來保持資料的一致性。

是的。外來鍵這種約束關係不在由資料庫幫你保持維護,由應用程式維護。

外來鍵的定義就是在乙個表中的字段是另外一張表中的主鍵。如果僅按照"不使用外來鍵"這幾個字的字面理解,就是要把外來鍵字段抽取出來放在一張中間表中。簡單說就是都當成多對多來處理。

不是的。怎麼建表還是和原來一樣,只不過在需要建立外來鍵約束的地方不建立外來鍵約束而已。

比如我們原來建表語句是這樣的:

create table `user` (

`user_id` int(11) not null auto_increment comment '主鍵',

`user_name` varchar(50) not null default '' comment '使用者名稱',

primary key (`user_id`)

) engine = innodb charset = utf8;

create table `order` (

`id` int(11) not null auto_increment comment '主鍵',

`total_price` decimal(10, 2) not null default '0.00',

`user_id` int(11) not null default '0',

primary key (`id`),

key `for_indx_user_id` (`user_id`),

constraint `for_indx_user_id` foreign key (`user_id`) references `user` (`user_id`)

) engine = innodb charset = utf8;

不用外來鍵約束後:

create table `user` (

`user_id` int(11) not null auto_increment comment '主鍵',

`user_name` varchar(50) not null default '' comment '使用者名稱',

primary key (`user_id`)

) engine = innodb charset = utf8;

create table `order` (

`id` int(11) not null auto_increment comment '主鍵',

`total_price` decimal(10, 2) not null default '0.00',

`user_id` int(11) not null default '0',

primary key (`id`)

) engine = innodb charset = utf8;

不用外來鍵約束後,為了加快查詢我們通常會給不建立外來鍵約束的字段新增乙個索引。

create table `order` (

`id` int(11) not null auto_increment comment '主鍵',

`total_price` decimal(10, 2) not null default '0.00',

`user_id` int(11) not null default '0',

primary key (`id`),

key `idx_user_id` (`user_id`)

) engine = innodb charset = utf8;

如果你理解了,你下面的問題就自然而然不存在了。

避免使用外來鍵,可以在插入資料時通過程式維持約束關係。

使用外來鍵約束優點:

使用外來鍵約束缺點:

實際開發中,一般不會建立外來鍵約束。

**:

mysql約束與外來鍵 MySQL 外來鍵與約束

外來鍵的建立 建表如下 create table parent id int not null,primary key id type innodb create table child id int,parent id int,foreign key parent id references pa...

MySQL 外來鍵約束

建立測試主表.id 是主鍵.create table test main id int,value varchar 10 primary key id 建立測試子表.create table test sub id int,main id int,value varchar 10 primary k...

MySQL外來鍵約束

innodb型別表有乙個其他儲存引擎不支援的特性 外來鍵約束。當b表的外來鍵關聯到a表的主鍵時 表b是父表a表的子表 如果刪除了a表,那麼b中的外來鍵則仍然關聯著乙個不存在的表的主鍵。而外鍵約束則設定了當約束被破壞時應該應用的的規則,包括防止約束破壞。建立乙個外來鍵約束的語法是 foreign ke...