一、数据库约束
分为六种:
- NOT NULL:不能存储NULL值
- UNIQUE:
- DEFAULT:没有赋值的时候给默认值
- PRIMARY KEY:
- FOREIGN KEY
- CHECK
//not null约束:创建表时,指定某一列不能为空
//例如:name varchar(20) not null;
// 此时name不能再赋为空值;
//unique约束:指定某一列是唯一的
//例如:name varchar(20) unique;
// 此时表中不能出现重名的项;(默认情况下同一数据可以重复)
//default约束:设定默认值,没有设置默认是null
//例如:name varchar(20) default '未命名';
// 如果没有命名则表中自动设置为“未命名”;
//primary key约束:主键约束:表示一条记录的身份标识,用来和别的记录区分开
// 逐渐不能为空;不能重复;只能有一个;
//自增主键:auto_increment
//foreign key约束:外键约束:用于关联其他表的主键或唯一键;
总结:
- 默认值null可以通过default来修改;
- primary key不能为空,不能重复;
- 自增主键可以设置为null,也可以手动设置;
- 使用外键时,父表为空时,不能往子表插入数据;
二、新增与查询
//新增:将一个表中的数据插入到另一个表中;
// insert into 表名1(列名1,,...) select 列名1,... from 表名2;
//例如:insert into class (studentID,studentName) select ID,Name from student;
2.1、聚合查询
聚合函数:
- count(列名):返回查询到的数据的数量;
- sun(列名):返回查询到的数据的总和;
- avg(列名):返回到查询的数据的平均值;
- max(列名):返回到查询到的数据的最大值;
- min(列名):返回到查询到的数据的最小值;
//聚合查询:
//group by子句:
//例如:select gender,max(score),min(score),avg(score) from student group by genfer;
// 按照性别来分组;
//聚合之后查询:
//在group by子句分组之后,需要使用having进行再次筛选分组;
//例如:select gender,avg(score) from student group by gender having avg(score)>70;
// 查询性别和平均分并按照平均分在80以上通过性别分组;
2.2、联合查询
笛卡尔积:select * from 表名,表名2;
2.2.1、内连接
select 表名1.列名 , 表名2.列名 from 表名1 join 表名2 on 条件;
//例如:select score.student_id , student.student_id from student join score on student.student_id = score.score_id;
//select 表名1.列名,表名2.列名 from
2.2.2、外接连
外连接分为左外连接和右外连接
//左连接:使join左侧表1的数据全部显示出来
select 列名 from 表名1 left join 表名2 on 连接条件;
//右连接:是join右侧表2的数据全部显示出来
select 列名 from 表名1 right join 表名2 on 连接条件;
2.2.3、自连接
//在自身的表中查询,行转换成列查询
select * from 表名 as s1,表名 as s2;
自连接的情况下需要给表取别名;
2.2.4、子查询
//例如:
//当查询结果只有一个时,用‘=’
//select name,score from student where student.id = (select id from class where name = '张三');
//当查询结果有多个时,用‘in’;
select name from student where student.name in (select id from class where student.id = '123' or student.id = '456');
2.2.5、合并查询
//union去重:
//例如:年龄小于18或者成绩小于60
select * from student where age < 18
union
select * from student where score < 60;
//union all不去重:
//例如:年龄小于18或者成绩小于60
select * from studnet where age < 18
union all
select * from student where score < 60;
总结:
- 当有多个表进行条件筛选时,先join,后在on后面添加筛选条件;
- 内连接表示两张表共有的数据,左外连接表示join左侧数据全包含,右外连接表示join右侧数据都包含(没有则用null补充);
- 自连接时,需要给表取别名;
- 子查询只有一个结果用‘=’,多个结果用‘in’;
- union去重,union all不去重;