上一篇文章讲了关于DDL数据定义语言的相关操作,这篇文章,就来好好看看有关于数据库数据操作语言的定义与使用吧~
一、添加数据——insert
首先,我们创建一个学生表。
create table stu
(
id varchar(15) primary key comment "学生编号",
name varchar(20) not null comment "学生姓名",
sex enum('man','woman') default 'man' comment "学生性别",
age int default 22 comment "学生年龄"
);
结果如下图所示:
1、插入全部属性的数据,不带属性
insert into stu values(“001”,‘zhangsan’,‘man’,20);
2、插入全部属性的数据,要带属性
insert into stu(id,name,sex,age) values(“001”,‘zhangsan’,‘man’,20);
3、插入个别属性的数据
错误方式!
insert into stu values(“002”,“lisi”,“woman”);属性没有一一对应
改进:insert into stu(id,name,sex) values(“002”,“lisi”,“woman”);
4、小批量的插入数据
nsert into stu values("002","lisi","woman",19),
("003","wangwu","man",22),
("004","zhaoliu","man",21),
("005","kaixin","woman",18),
("006","gaoxin","man",23);
二、删除数据——delete
1、删除所有数据
delete from stu;
2、过滤条件
delete from stu where id = “006”;
三、修改数据——updata
1、所有满足
update stu set sex = “man”;
2、过滤条件
update stu set age = 19 where id = “002”;
四、查询数据——select
1、普通查询
1.1有通配符的查询:不建议使用
select * from stu;
2、具体查询某个字段
select id, name, sex, age from stu;效果同上图
3、过滤条件
select * from stu where id = “001”;
2、去重查询 distinct
为了解决数据过大冗余问题
select distinct age from table_name;
3、排序 order by
升序 asc 降序 desc ,默认是升序
select distinct age from stu order by age;
以上的查询都是单表查询,接着我们要引出等值查询、连接查询等概念,所以我们在此再创建一个学生成绩表result.
result相关信息如下:
insert into result values("001","p01",78),
("001","p02",56),
("002","p01",34),
("002","p02",89),
("003","p01",78),
("003","p02",57);
4.分组查询 group by
查询每个学生的课程总分
分析:
select id,Sum(score) from result group by id;
5、连接查询
查询年龄小于20岁学生的不及格成绩
如果直接连接查询的话
select stu.id,score
from stu,result
where stu.id = result.id and age < 20 and score < 60;
分析:这样他会按照笛卡尔乘积的方式来查找数据,如下图,效率非常低
5.1外连接查询
5.1.1左外连接查询:左表过滤的结果必须全部存在,
select a.id,score
from
(select id,age from stu where age < 20) a
left join
(select id, score from result where score < 60) b
on a.id = b.id
where b.score is not null;
5.1.2右外连接查询:左表过滤的结果必须全部存在
select a.id,score
from
(select id,age from stu where age < 20) a
right join
(select id,score from result where score < 60) b
on a.id = b.id
5.1.3全外连接查询
select a.id,score
from
(select id,age from stu where age < 20) a
full join
(select id,score from result where score < 60) b
on a.id = b.id
where a.id is not null;
5.2 内连接查询 只筛选匹配项
select a.id,score
from
(select id,age from stu where age < 20) a
inner join
(select id,score from result where score < 60) b
on a.id = b.id;
6、聚合查询:union 他有自动去除重复项的功能
查询全校师生的信息
select * from stu
union
select * from teach;