主键自增长、外键约束、级联更新

1)自动增长(配合int类型的主键使用, 自增后的id值取决于上一条)
	(1)如果某一列是数值类型的,使用auto_increment可以来完成值的自动增长
	
	(2)创建表时,添加自动增长
		create table stu{
			id int primary key auto_increment, -- 给id添加主键约束
			name varchar(20)
		}

	(3)删除自动增长
		alter table stu modify id int;
	
	(4)添加自动增长
		alter table stu modify id int auto_increment;
		
2)外键约束
	不好的地方:
		(1)发现数据由冗余, 不太符合数据库设计的准则
		(2)修改不方便,比如: 想把研发部修改个名字
		
	改进: 设计为2个表(部门表和员工表)
	
	问题:
		zhangsan lisi wangwu 位于1号部门, 
		但是,1号部门的表格已经删除了
		
	解决办法: 因此外键约束的引入
	
	语法:
		create table 表名{
			外键列
			constraint 外键名称 foreign key 外键列名称 references 主表名称(主表主键名称)
		}
	
		如:
			create table employee(
				id int primary key auto_increment,
				dep_id int,
				constraient emp_dept_fk foreign key (dep_id) references deparences department(id)
			);
			
	删除外键:
		alter table employee drop foreign key emp_dept_fk;
	
	添加外键:
		alter table employee add constraint emp_dept_fk foreign key(dep_id) references department(id);
			
3)级联的操作(慎用,比较危险, 会把相关的记录都被删除, 性能也低下)
	(1)alter table employee add constraint emp_dept_fk foreign key(dep_id) references department(id)
			on update cascade on delete cascade; 
			
		
		笔记: 
			级联更新: on update cascade
			级联删除:  on delete cascade
			

			

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章