数据库操作增删查改(进阶)

1.数据库约束

not null:指示某列不能存储null值(创建表时,可以指定某列不为空) create table student (id int not null, name varchar(20));
unique:唯一约束(如果尝试插入重复的值,就会报错) create table student (id int unique, name varchar(20));
default:默认值约束(此处可以把默认值改成需要的内容) create table student (id int , name varchar(20) default unknown);
primary key:主键约束(相当于not null + unique) create table student (id int primary key, name varchar(20)); 为了保证主键不重复,可以借助数据库自动来生成(auto_increment) create table student (id int primary key auto_increment, name varchar(20)); 自增的特点: 1)如果表中没有任何的记录,自增从1开始 2)如果表中已经有记录了,自增从上一条记录往下自增 3)如果中间的某个数据删了,再次插入数据,刚才被删掉的自增主键的值不好被重复利用
foreign key:外键约束,描述两张 表的之间的关联关系,外键用于关联其他表的主键或唯一键 foreign key (字段名) references 主表(列) 例:create table class (id int primary key auto_incrament, name vaecahr(20)); create table student (id int primary key auto_increment, name varchar(20), classId int, foreign key (classId) reference class(id));
check约束:MySQL使用时不报错,但忽略该约束 create table user_test ( id int, name varchar(20), sex varchar(1), check (sex =男 or sex=女));

 2.表的设计

1)一对一(一个人只能有一个身份证,一个身份证对应一个人)

2)一对多(一个班级有很多学生,但一个学生只能有一个班级)

3)多对多(一个学生可以选多门课程,一门课程也可以被多名学生选择)

3.新增

insert into [表名] select [列名] [列名] ..... from [表名];

4.聚合查询 

1)count:返回查询到的数据的数量 2)sum:返回查询到的数据的总和 3)AVG:返回查询到的数据的平均值 4)max:返回查询到的数据的最大值 5)min:返回查询到的数据的最小值 select [函数名](列名) from [表名];

5.分组查询 

group by:select 中使用group by字句可以对指定列进行分组查询,搭配where使用(先判断条件再分组) having:在进行分组以后,需要对分组结果再进行条件过滤(先分组再判断条件)

6.联合查询

实现联合查询的基本机制:笛卡尔积

内连接:select [字段] from 表1 ,表2 where [条件]; select [字段] from 表1 inner join [表2] on [条件]; 字段:可以是[表名.列名] 外连接:分为左连接与右连接 左连接:select [字段名] from 表1 left join 表名2 on [条件]; 右连接:select [字段名] from 表1 right join 表名2 on [条件];

7.自连接

自连接的本质就是把行与行之间的比较条件转换成列与列

8.子查询

子查询是指嵌入在起他sql语句中的select语句,也叫嵌套查询

select [列名] from [表名] where [列名] = (select [列名] from [表名] where [条件]);

9.合并查询

相当于把多个查询的结果集合合并成一个集合,可以使用集合操作符union,union all

两种情况相等: select [列名] from [表名] where [条件] or [条件]; select [列名] from [表名] where [条件] union select [列名] from [表名] where [条件]; union:如果两个查询结果中存在相同的记录,就只会保留一个,union自动去重; union all :不自动去重;
经验分享 程序员 微信小程序 职场和发展