mysql 無法建立外來鍵約束

2021-06-09 06:32:14 字數 698 閱讀 6887

對mysql資料庫不太熟悉,今天遇到了外來鍵建立問題。alter外來鍵建立語句命令列下提示成功了,但就是沒看到外來鍵。

後來改用workbench工具來建立,發現是因為資料預設是採用的myisam儲存引擎,該引擎不支援外來鍵,需要修改引擎為innodb才可以。

我直接在workbench將表的引擎改為了innodb,發現還是不行,報1005錯誤:

10:31:56	alter table `cm_relation_contact_group`     add constraint `fk_test`    foreign key (`groupid` )    references `cm_group` (`id` )    on delete no action    on update no action  , add index `fk_test` (`groupid` asc)	error code: 1005. can't create table 'callcenter.#sql-728_5c92' (errno: 150)
1、外來鍵的引用型別不一樣,主鍵是int外來鍵是char 

2、找不到主表中 引用的列 

3、主鍵和外來鍵的字元編碼不一致 

4.還有要建立外來鍵的話,要先建立索引。沒有建立索引也會出錯。

我逐個檢查了下,都沒問題。難道是每個表都有引擎設定,開啟被引用表,發現引擎還是myisam,修改過來後就ok了。

mysql建立外來鍵約束

mysql建立關聯表可以理解為是兩個表之間有個外來鍵關係,但這兩個表必須滿足三個條件 1.兩個表必須是innodb資料引擎 2.使用在外鍵關係的域必須為索引型 index 3.使用在外鍵關係的域必須與資料型別相似 例如 1 建立s user表 create table s user u id int...

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