1.where函数语句
单表查询
where可以查询单个表中某个特定值的数据或者符合某些条件的信息
|
例1:查询名字叫王淑芬的学生信息
select * from student where name='王淑芬'; ---输出王淑芬的信息
例2:查询所有女生的学生信息
select * from student where sex='女'; ---输出结果为所有女生的信息
例3:查询出生地为广州的男生信息
select * from student where born_in='广州' and sex='男'; ---输出赵永帅的信息
两个表或多表查询
可以查询两个表中有共同属性的数据信息
stu_info表 | |||||
ID | STU_ID | NAME | MAJOR | TEACHER | HOUSE |
1 | 20150010201 | 张勇 | 英语 | 刘欢 | 610 |
2 | 20150010202 | 李阳 | 数学 | 邓稼先 | 610 |
3 | 20150010203 | 李玲玉 | 工商管理 | 钱钟书 | 801 |
4 | 20150010204 | 秦天福 | 化工 | 金庸 | 612 |
5 | 20150010205 | 欧阳娜拉 | 计算机技术 | 谭浩强 | 801 |
6 | 20150010206 | 王淑芬 | 软件工程 | 王建民 | 801 |
7 | 20150010207 | 赵永帅 | 物理 | 钱学森 | 612 |
8 | 20150010208 | 钱永琪 | 工商管理 | 钱钟书 | 802 |
9 | 20150010209 | 华天硕 | 计算机技术 | 谭浩强 | 612 |
10 | 20150010210 | 江疏影 | 英语 | 刘欢 | 802 |
例1: 查询江疏影的专业信息
select * from stu_info where istu_id in ( select stu_id from student where name='江疏影');
---输出结果为sut_info表STU_ID为20150010210信息
例2:查询所有的学生基本信息和专业信息
select * from student a,stu_infob where a.stu_id=b.id; ---输出结果为两个表中所有的信息,且一一对应
2.sum/max/min/avg/count函数使用
当统计某些数据的总和、最大数、最小数及平均以及总数的时候,就需要用到这些函数
sut_score | ||||||
ID | STU_ID | NAME | CHINESE | MATH | ENGLISH | POLITICAL |
1 | 20150010201 | 张勇 | 86 | 92 | 58 | 73 |
2 | 20150010202 | 李阳 | 81 | 53 | 78 | 80 |
3 | 20150010203 | 李玲玉 | 73 | 78 | 73 | 71 |
4 | 20150010204 | 秦天福 | 60 | 86 | 67 | 78 |
5 | 20150010205 | 欧阳娜拉 | 69 | 61 | 69 | 67 |
6 | 20150010206 | 王淑芬 | 88 | 73 | 73 | 73 |
7 | 20150010207 | 赵永帅 | 91 | 79 | 87 | 77 |
8 | 20150010208 | 钱永琪 | 78 | 81 | 59 | 81 |
9 | 20150010209 | 华天硕 | 66 | 95 | 65 | 69 |
10 | 20150010210 | 江疏影 | 67 | 47 | 82 | 76 |
例1:获取李玲玉的总分
select sum(CHINESE+MATH+ENGLISH+POLITICAL ) from sut_score where name='李玲玉'; ---输出为李玲玉四门学科分数的总和
例2:获取所有学员政治的总分
select sum(POLITICAL ) fromsut_score ;
例3:获取英语的最高分数
select max(ENGLISH) fromsut_score ;
例4:获取数学的最低分
select min(MATH) fromsut_score ;
例5:获取语文的平均分
selectavg(CHINESE) fromsut_score ;
例6:获取班级中的总人数
select count(*) from sut_score ;
select count(1) from sut_score ;
3.group by函数
group by函数往往和count,avg等函数联合使用,且在数据量较大时使用
表数据同上张表
例1:统计语文各个分数的人数
select count(1),chinese from stu_score group by chinese; ---输出结果为语文每个分数的人数
4.union与union ALL函数
union和union all都是查询两个表中相同字段值的数据,所以union语句局限性较大。另外需要注意的是union是去重且排序的,union all不去重且不排序。
例1:拿上面的student表和stu_info表来举例,获取两张表的相同的STU_ID和NAME的数据、
select name,sut_id from student union select name,sut_id from su_info;
select name,sut_id from student union all
select name,sut_id from su_info;
union两边的语句也可以加上where判断条件。
5.update函数
update函数在代码开发过程中以及测试过程中经常被用到,将数据库中的信息更新为最新的数据。
例1:华天硕和张勇的宿舍互换了一下,请更新数据
update stu_info set house='612' where name='张勇';
update stu_info set house='610' where name='华天硕';
update stu_info set house='610' where name='华天硕';
6.like函数
like函数通常是查找一些类似的值。
例1:查找stu_info表中姓名的包含天的人员姓名列表
select * from stu_info where
name like
'%天%'; --结果为秦天福和华天硕的信息
7.DISTINCT函数
distinct函数是去除重复的值的数据。
例1:将学生成绩表中英语成绩分数由高到低排序且去除重复的。
select distinct ENGLISH from sut_score order by ENGLISH desc;