MySql外來鍵約束詳解

2021-06-27 20:26:06 字數 988 閱讀 7496

這裡是講講如何正確使用mysql的外來鍵約束。

定義乙個外來鍵約束必須滿足以下的條件:

1)主表和從表必須是innodb型。

2)所有要建立外來鍵的字段必須建立索引,用於外來鍵的列一般都是主鍵,主鍵會預設新增索引。

3)主表和從表之間建立外來鍵約束的列,約束條件必須完全比配。

使用示例:

# 主表,部門

drop table if exists department;

create table department(

# 條件2:索引

id int unsigned not null auto_increment primary key,

name varchar(50)

)# 條件1:innodb

engine=innodb;

# 從表,員工

drop table if exists employee;

create table employee(

id int unsigned not null auto_increment primary key,

name varchar(50),

# 條件3:約束條件必須完全比配

department int unsigned not null,

constraint employee_fk foreign key(department) references department(id) on update set null on delete set null,

# 條件2:索引

index(department)

)engine=innodb;

如果在建立表的時候出現如下錯誤:

error 1005 (hy000): can't create table '資料庫名.表名' (errno: 150)

那麼很有可能是你的建表語句沒有滿足上面的3個要求。

mysql 外來鍵詳解 MySQL的外來鍵約束詳解

外來鍵的作用 主要作用有兩個,乙個保證資料的完整性和一致性,乙個是方便一些er圖生成工具生成更具可讀性的er圖。注意 引入外來鍵可能會導致效能下降 mysql中的外來鍵 mysql有兩種常用的引擎型別 myisam和innodb。目前只有innodb引擎型別支援外來鍵約束。innodb中外鍵約束定義...

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...