一、语法结构

select [ , ]     from 表名
where 条件查询
group by 分组
having 分组条件
order by 排序
limit 限制输出

二、select语法结构的基本子句

        1、select子句:用于指定返回的列

*                   通配符,返回所有列的值

all                显示所有的行,包括重复行

distinct        消除重复行

列名            指定返回结果的列,多列用逗号隔开 

# 使用通配符
select * from student;

#使用distinct消除重复行
select distinct id from student;

#使用as定义查询列的别名
select count(*) as ‘男生人数’ form student where sex =‘男’;

#查询特定的列
select id,name from student;

        2、where子句

        指定查询的条件,where必须紧跟在from子句后面!!

#查询生日在1999-01到2000-05之间的学生
select * from student where birth between ‘1999-01’ and ‘2000-05’;

#查询学号为001或005的学生
select * from student where id in ('001','005');

        3、group by子句

        根据字段进行分组统计,将同类分组汇总成一行。

        若指定为多列分组,则先按照指定的第一列进行分组在对指定的第二列进行分组。

#求选秀的各门课程的平均成绩和选秀该课程的人数
select kc,avg(cj)as ‘平均成绩’,count(kc)as ‘选修人数’
from score group by kc;

        4、having子句

        用在group by后面选择行。

#选修1门以上课程学生的学号
select id form score 
group by kc
having count(kc) > 1;

        5、order by子句

        按照一定顺序排序。asc为升序(默认),desc降序

#按照成绩降序排列出选修1课程的学生学号成绩
select id,cj form score where kc = ‘1’
order by cj desc;

        6、limit子句

        限制被select语句返回的行数

#查询课程号为001成绩前五的学生学号和成绩
select id,cj from student where kc = ‘001’
order by cj desc limit 5;

三、聚合函数

常见聚合函数

功能

sum()

计算某列值得总和

count()

计算某列值得个数

avg()

计算某列值的平均数

max()

计算某列值的最大值

min()

计算某列值的最小值

variance()

计算特定的表达式的左右值的方差

        需要注意的是上面所有的聚合函数都不把空值所在行计算在内,只对列中的非空值进行计算。

四、多表联合查询

        1、全连接

        连接方式将各张表用逗号分隔,用where子句设定条件进行等值连接

语法格式:
select 表名.列名,表名.列名…… from 表1,表2  where 连接条件

# 查找学生选过的课程名和课程号
select distinct course.c_no,course.c_name from course,score
where course.c_no = score.c_no;

        2、join连接

1、内连接 inner join
select t_name,c_name
from teachers inner join teach on teachers.t_no = teach.t_no
inner join course on teach.c_no = course.c_no

2、外连接 outer join
又分为左连接left outer join 和右连接 right outer join

五、嵌套查询

        1、嵌套在where子句中

查询信息学院的学生信息
select * from student where 
xy = (select xy from school where xy = '信息学院‘;

2、嵌套在form中
从student表中查询成绩在80-90之的学生
select s_no,c_no,report
from (select s_np,c_no.report
from score
where score >80 and score <90) as stu;

六、联合查询

union 联合查询
连接查询1990302 和1990303学生的信息
select s_no as 学号,s_name as 姓名
from student
where s_no = 1990302
union 
select s_no as 学号,s_name as 姓名
from student
where s_no = 1990303