数据库技术mysql能干什么_MySQL外键有什么作用
MySQL外鍵的作用:
保持數據一致性,完整性,主要目的是控制存儲在外鍵表中的數據。使兩張表形成關聯,外鍵只能引用外表中列的值!
我們來建兩個表
CREATE TABLE `example1` (
`stu_id` int(11) NOT NULL DEFAULT '0',
`course_id` int(11) NOT NULL DEFAULT '0',
`grade` float DEFAULT NULL,
PRIMARY KEY (`stu_id`,`course_id`)
);
CREATE TABLE `example2` (
`id` int(11) NOT NULL,
`stu_id` int(11) DEFAULT NULL,
`course_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `f_ck` (`stu_id`,`course_id`),
CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example1` (`stu_id`, `course_id`)
);
insert into example1 (stu_id,course_id,grade)values(1,1,98.5),(2,2,89);
insert into example2 (id,stu_id,course_id)values(1,1,1),(2,2,2);
我們建了
example1表,里面包含stu_id學號,course_id課程號,grade分數
example2表,里面包含id,stu_id學號,course_id課程號,然后建立外鍵
分別插入數據到兩個表中。
我們把example2中的stu_id和course_id稱為example2表的外鍵,example1是父表,example2是字表,兩個表形成關聯,必須字表的數據刪除后,才能刪除父表中的對應數據
現在我們來刪除example1中的一條數據
delete from example1 where stu_id=2;
會發現報錯
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`example3`, CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example2` (`stu_id`, `course_id`))
因為example2中的數據關聯了example1的數據,這樣是刪不了的,達到了外鍵的作用;
然后我們來先刪除example2表中的數據,再刪除example1表中的數據
delete from example2 where stu_id=2;
delete from example1 where stu_id=2;
這樣就成功了;
事件觸發限制:
on delete和on update , 可設參數cascade(跟隨外鍵改動), restrict(限制外表中的外鍵改動),set Null(設空值),set Default(設默認值),[默認]no action
我們來看看事件觸發限制是干嘛的。。。
我們先刪除外鍵,然后重新建立外鍵帶上事件觸發限制
alter table example2 drop foreign key f_ck;
alter table example2 add CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example1` (`stu_id`, `course_id`) ON DELETE CASCADE ON UPDATE CASCADE;
我們先查看一下數據
mysql> select * from example1;select * from example2;
+--------+-----------+-------+
| stu_id | course_id | grade |
+--------+-----------+-------+
|? ? ? 1 |? ? ? ? 1 |? 98.5 |
+--------+-----------+-------+
1 row in set (0.00 sec)
+----+--------+-----------+
| id | stu_id | course_id |
+----+--------+-----------+
|? 1 |? ? ? 1 |? ? ? ? 1 |
+----+--------+-----------+
1 row in set (0.00 sec)
這時example1和example2中的stu_id和course_id都是1,
再來修改example1表中的數據看看
update example1 set stu_id=3,course_id=3 where stu_id=1;
再來查看數據
mysql> select * from example1;select * from example2;
+--------+-----------+-------+
| stu_id | course_id | grade |
+--------+-----------+-------+
|? ? ? 3 |? ? ? ? 3 |? 98.5 |
+--------+-----------+-------+
1 row in set (0.00 sec)
+----+--------+-----------+
| id | stu_id | course_id |
+----+--------+-----------+
|? 1 |? ? ? 3 |? ? ? ? 3 |
+----+--------+-----------+
1 row in set (0.00 sec)
發現沒,example1和example2中的stu_id和course_id都變成了3
我們在來刪除example1表中的數據
delete from example1 where stu_id=3;
會發現可以刪除,而且example2中的數據也沒有了;
其實啊,外鍵就這個作用,保持數據一致性,完整性,是不讓改還是一起改,由事件觸發器決定;
總結
以上是生活随笔為你收集整理的数据库技术mysql能干什么_MySQL外键有什么作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python作业网站_python大作业
- 下一篇: mysql 1366 hy000_ERR