MYSQL字段约束之外建约束参考操作

MYSQL字段约束之外建约束参考操作
1,CASCADE:从父表删除或更新且自动删除或更新子表中匹配的行
    格式: ON UPDATE | DELETE CASCADE 
2, SET NULL: 从父表删除或更新,并设置子表中的外键列为null。如果使用该选项必须保证子表列没有指定NOT NULL;
3,RSETRICT: 拒绝对附表的删除或更新操作
4,NO ACTION : 标准SQL的关键字,在MYSQL中与RESTRICT相同;

1,创建从表
mysql> CREATE TABLE user1(
    -> id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    -> username CHAR(10) NOT NULL,
    -> cid INT UNSIGNED,
    -> FOREIGN KEY (cid) REFERENCES corse (id) ON DELETE CASCADE
    -> );
Query OK, 0 rows affected (0.10 sec)


2,从表自动创建显示,设置物理外键约束
CONSTRAINT `user1_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `corse` (`id`) ON DELETE CASCADE
mysql> show create table user1;
| user1 | CREATE TABLE `user1` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` char(10) NOT NULL,
  `cid` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cid` (`cid`),
  CONSTRAINT `user1_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `corse` (`id`) ON DEL
ETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |

3,主表插入属性值;
mysql> SELECT * FROM  corse;
+----+------------+
| id | name       |
+----+------------+
|  1 | shuaishuai |
|  2 | shuaige    |
|  3 | shuaibi    |
|  4 | dashuai    |
+----+------------+
4 rows in set (0.00 sec)

4,从表插入属性值;
mysql> select * from user1;
+----+-----------+------+
| id | username  | cid  |
+----+-----------+------+
|  1 | daxiong   |    1 |
|  2 | jingxiang |    2 |
|  3 | jiqimao   |    3 |
|  4 | 多啦爱梦  |    4 |
+----+-----------+------+
4 rows in set (0.05 sec),

5,删除主表中的行值;
mysql> delete from corse WHERE id=1;

6,查询从表中的变化;对应的外键值也被删除或更新;
mysql> select * from corse;
+----+---------+
| id | name    |
+----+---------+
|  2 | shuaige |
|  3 | shuaibi |
|  4 | dashuai |
+----+---------+
3 rows in set (0.00 sec)

mysql> select * from user1;
+----+-----------+------+
| id | username  | cid  |
+----+-----------+------+
|  2 | jingxiang |    2 |
|  3 | jiqimao   |    3 |
|  4 | 多啦爱梦  |    4 |
+----+-----------+------+
3 rows in set (0.00 sec)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值