mysql取消外碼約束 MySQL刪除外來鍵約束問題

2021-10-25 14:45:23 字數 1113 閱讀 6494

當我們在乙個表中新增字段約束的時候:

alter table product add constraint product_fk foreign key(category_id) references category(id);

會認為我的外來鍵約束名稱為product_fk, 然後當我們想刪除時:

alter table product drop foreign key product_fk;

會出現以下的錯誤:

query: alter table product drop foreign key product_fk

error code: 1025

error on rename of '.\web_day09\product' to '.\web_day09\#sql2-2330-1' (errno: 152)

這是因為欄位的外來鍵約束名並不是product_fk 。我們在資料庫中執行一下命令:

show create table product

控制台會顯示

table create tableproduct

create table `product` (

`pid` varchar(32) not null,

`pname` varchar(40) default null,

`price` double default null,

`category_id` varchar(32) default null,

primary key (`pid`),

key `category_id` (`category_id`),

constraint `product_ibfk_1` foreign key (`category_id`) references `category` (`cid`)

) engine=innodb default charset=utf8

從建表語句中我們發現外來鍵約束名稱是:

product_ibfk_1

然後我們再執行外來鍵刪除操作

alter table product drop foreign key product_ibfk_1

0 row(s) affected

原文出處:

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如何處理外碼約束

建立測試主表.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怎麼約束 mysql 約束

4 約束 1 對乙個列新增的約束叫列級約束。對兩個或兩個以上的列新增的約束叫做表級約束。2 表級約束只能在字段後面新增,列級約束既可以新增在字段後面,也可以在最後新增。3 非空 預設只存在列級約束。主鍵 唯 一 外來鍵都既有表級約束又有列級約束。4 約束有 primary key 主鍵 unique...