MySQL foreign_key_checks,unique_checks

1.foreign_key_checks控制是否进行外键约束检查。

mysql> show variables like 'foreign_key_checks';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| foreign_key_checks | ON    |
+--------------------+-------+
1 row in set (0.01 sec)

mysql> create table sam(id int primary key,name varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> create table tom (id int primary key,fk_id int,foreign key(fk_id) references sam(id)); 
Query OK, 0 rows affected (0.02 sec)
 
mysql> insert into sam values (1,'sam');
Query OK, 1 row affected (0.00 sec)

mysql> insert into sam values (2,'tom');
Query OK, 1 row affected (0.00 sec)

mysql> insert into tom values (1,3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`sam`.`tom`, CONSTRAINT `tom_ibfk_1` FOREIGN KEY (`fk_id`) REFERENCES `sam` (`id`))

mysql> set foreign_key_checks=0;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into tom values (1,3);
Query OK, 1 row affected (0.00 sec)

2.unique_checks名义上控制唯一约束检查,但实际上并不起作用,MySQL始终都会进行唯一性检查。

mysql> create table sam(id int primary key,name varchar(10) unique);
Query OK, 0 rows affected (0.09 sec)

mysql> desc sam;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| name  | varchar(10) | YES  | UNI | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> show variables like 'unique_checks';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| unique_checks | ON    |
+---------------+-------+
1 row in set (0.05 sec)

mysql> insert into sam values (1,'sam');
Query OK, 1 row affected (0.00 sec)

mysql> insert into sam values (1,'sam');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

mysql> set unique_checks=0;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into sam values (1,'sam');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
mysql> show variables like 'unique_checks';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| unique_checks | OFF   |
+---------------+-------+
1 row in set (0.00 sec)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值