mysql 设置外键约束SET FOREIGN_KEY_CHECKS=1
1.问题描述:Mysql中如果表和表之间建立的外键约束,则无法删除表及修改表结构
解决方法:
在Mysql中取消外键约束: SET FOREIGN_KEY_CHECKS=0;
然后将原来表的数据导出到sql语句,重新创建此表后,再把数据使用sql导入,
然后再设置外键约束: SET FOREIGN_KEY_CHECKS=1;
2. MySQL 5.1.48 导入 MySQL 5.7.18 时遇到 T FOREIGN_KEY_CHECKS = 0 错误的解决方法
#1064 – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘T FOREIGN_KEY_CHECKS = 0’ at line 1
经查询,这个是 mysql 启动和关闭外键约束的方法,去掉即可。
编辑数据库文件:
//去掉此行
SET FOREIGN_KEY_CHECKS = 0;
//去掉此行
SET FOREIGN_KEY_CHECKS = 1;
然后重新导入即可。
3.查看当前FOREIGN_KEY_CHECKS的值可用如下命令
SELECT @@FOREIGN_KEY_CHECKS;
4.外键使用实例
CREATE TABLE cities
(
name VARCHAR(90),
state CHAR(2) REFERENCES states
) ENGINE = InnoDB;
-- Query OK, 0 rows affected (0.05 sec)
-- Let's see DDL 查看表结构
SHOW CREATE TABLE cities;
-- It does not have FOREIN KEY constraint 此时没有外键约束
CREATE TABLE `cities` (
`name` varchar(90) DEFAULT NULL,
`state` char(2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You have to use FOREIGN KEY clause in CREATE TABLE to specify a foreign key in MySQL:
//您必须在CREATE TABLE中使用外键子句来指定MySQL中的外键:
DROP TABLE IF EXISTS cities; #删除原来创建的表
CREATE TABLE cities
(
name VARCHAR(90),
state CHAR(2),
FOREIGN KEY (state) REFERENCES states(abbr)
) ENGINE = InnoDB;
-- Let's see DDL now
SHOW CREATE TABLE cities;
-- Now the table has FOREIGN KEY 现在表中有了外键
CREATE TABLE `cities` (
`name` varchar(90) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
KEY `state` (`state`),
CONSTRAINT `cities_ibfk_1` FOREIGN KEY (`state`) REFERENCES `states` (`abbr`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
赞赏码
非学,无以致疑;非问,无以广识