一、查询实例
1、select 查询字段 from 表名 where 查询条件
举例说明:
表名:student
表中字段:id,name,age,score,subject,class
表中数据:
(1,"Sheldon",18,99,"Maths", "one"),
(1,"Sheldon",18,90,"Chinese","one"),
(1,"Sheldon",18,85,"English","one"),
(2,"Kim",20,89,"Maths","two"),
(2,"Kim",20,95,"Chinese","two"),
(2,"Kim",20,92,"English","two");
1)查询出某条件下的所有信息
# 查询出表student中age为18的所有学生信息
select * from student where age=18
2)求和
# 计算并查询出表student中name为Sheldon的学生的总分数
select sum(score) from student where name="Sheldon"
3)求平均数
# 计算并查询出表student中name为Sheldon的学生的平均分数
select avg(score) from student where name="Sheldon"
4)求最小值:
# 计算并查询出表student中name为Sheldon的学生的最低分数
select min(score) from student where name="Sheldon"
5)求最大值
# 计算并查询出表student中name为Sheldon的学生的最高分数
select max(score) from student where name="Sheldon"
6)对查询结果排列
#查询出表student中name为Sheldon的学生的信息,且按照分数倒序排列(desc是逆序排序,asc是正序排序,asc可省略不写)
select * from student where name="Sheldon" order by score desc
7)求总数(未去重)
# 计算并查询出class为one的班级学生总数(实际上只有一个学生)
select count(*) from student from where class="one"
8)求总数(去重)
# 去重统计出class为one的班级学生总数
select count(distinct id) from student
9)根据一个或多个列表字段进行分组统计查询:
# 统计每个班19岁以上的学生人数(执行顺序where过滤->分组->聚合函数)
select class,count(distinct age) from student where age>19 group by class
表student如下:
10)多表连接查询:
表student如下:
表info如下:
# 两个表连接,并去掉重复的列
select a.*,b.address from student a join info b on a.id=b.id
11)嵌套查询:
# 查询出所有学生的id,name和address
select a.id,a.name,(select b.address from info b where a.id=b.id) address from student a
或者也可以用:
select a.id,a.name,b.address from student a,info b where a.id=b.id
二、插入、修改和删除实例
1.插入:
# 插入多条数据
insert into student values
(1,"Sheldon",18,99,"Maths", "one"),
(1,"Sheldon",18,90,"Chinese","one"),
(1,"Sheldon",18,85,"English","one"),
(2,"Kim",20,89,"Maths","two"),
(2,"Kim",20,95,"Chinese","two"),
(2,"Kim",20,92,"English","two");
2.修改:
# 修改Kim的Maths分数为92
update student set score=92 where name="Kim" and subject="Maths"
3.删除:
# 删除Kim的English信息
delete from student where name="Kim" and subject="English"