约束

概念

* 对表中的数据进行限定, 保证数据的正确性 完整性和有效性

分类:

* 主键约束 primary key
* 非空约束 not null
* 唯一约束 unique
* 外键约束 foreign key

非空约束

1. 创建表时添加约束
    create TABLE stu (
        id int,
        name varchar(20) NOT NULL
    );
	* 修改 alter table sstu modify name varchar(20);

唯一约束

* 值不能重复
* null 可以重复 mysql 中 null 表示不确定
* alter table stu drop index phone_num;修改
* alter table stu modify phone_num varchar(20) unique;  创建表后添加唯一约束
create table studet (
    id int,
    phone_num varchar(11) unique;
);

主键约束

1. 注意:
	1. 含义: 非空企且唯一
	2. 一张表 只能有一个主键
	3. 主键就是表中记录的唯一标识
2. 创建表时添加主键
	* create table stu(
		id int primary key, -- id 主键约束
		name varchar(20)
	  ); 
3. 删除
	* alter table stu drop primary key;
4. 创建后添加主键
	* alter table stu modify id int primary key;
5. 自动增长
	1. auto_increment;

外键约束

* foreign key
1.	语法
	create table 表名(
		...
		外键列
		constraint 外键名称 foreign key 外键列名称 references 主表名称(主表列名称)
	);
2. 删除外键
	* alter table 表名 drop  foreign key 外键名;
Last Updated: 8/4/2020, 6:23:45 PM