
- 15.1 约束概念:限定数据库中数据的一套规则
- 15.2 约束作用:保证数据的准确性、完整性、可靠性、联动性
- 15.3 数据库常用约束:
- 主键约束
- 作用:让数据具有唯一标识
- 语法:
create table table_primarykey
(
id int primary key
)
- 特点:自动设置非空约束
- 自动增长
- 作用:使数据自动增长,一般给主键设置
- 语法:
create table table_autoincrement
(
id int primary key auto_increment
)
- 唯一约束
- 作用:保证数据的准确性
- 语法:
create table table_unique
(
qqnumber int unique
)
- 特点:可以为多列设置唯一约束
- 非空约束
- 作用:保证数据不为空
- 语法:
create table table_notnull
(
name varchar(30) not null
)
- 默认约束
- 作用:给字段设置默认值
- 语法:
create table table_default
(
sex char(2) default ‘男’
)
- 检查约束
- 作用:检查数据的完整性
- 语法:
create table table_check
(
sex char(2) check(‘男’ or ‘女’)
)
create table table_enum
(
sex enum(‘男’,’女’)
)
- 外键约束
- 作用:让两表之间产生联动关系
- 语法:
create table class
(
id int primary key auto_increment,
classname varchar(30) not null
)
create table score
(
id int primary key auto_increment,
chinese_score int not null,
foreign key(id) references class(id)
)
-
要想删除class
表和score表,首先要删除score表
16. 为数据增补约束
- 16.1
添加/
删除主键约束
- 添加主键约束
-
语法:alter table table_name add constrain con_name primary key(col_name)
- 删除主键约束
- 16.2 外键约束
- 添加外键约束
-
语法:alter table table_name add constrain con_name foreign key(col_name) references table(col_name)
- 删除外键约束
- 16.3 检查约束
- 添加检查约束
-
语法:alter table table_name add constraint con_name check(expression)
- 删除检查约束
- 16.4
默认约束
- 添加默认约束
-
语法:alter table table_name alter col_name default value
- 删除默认约束
- 16.5
自动增长
- 添加自动增长
-
语法:alter table table_name modify column col_name type auto_increment
- 删除自动增长
17. 条件查询
- 17.1 普通条件查询
-
语法:select * from table where expression
- where
:将查询到的数据,通过where后的expression一条一条的进行筛选,符合要求则显示,不符合要求则去除。
