Select 结构:
句子结构: | Select 列名 [all/distinct] | from 表名 | where 条件 | group by 按该列数值分组 | having 聚合条件 | order by 升序/降序 |
---|---|---|---|---|---|---|
执行优先级 | 5 | 1 | 2 | 3 | 4 | 6 |
关键字说明:
子句 | 执行顺序 | 必填/选填 | 说明 |
---|---|---|---|
SELECT | 5 | 必填 | 决定最终返回的列,可使用聚合函数、表达式、别名 |
[all/distinct] | 5.1 | 选填 | 是否过滤重复项 |
FROM | 1 | 必填 | 指定数据源(表/视图),可包含 JOIN |
WHERE | 2 | 选填 | 行级过滤(不可用聚合函数) |
GROUP BY | 3 | 选填 | 分组依据(可多列),与聚合函数配合使用 |
HAVING | 4 | 选填 | 分组后过滤(可用聚合函数) |
ORDER BY | 6 | 选填 | 排序依据(ASC/DESC,可多列) |
例子
use stu
select count(*) 学生总数 from student;
select count(*) 年龄大于20学生总数 from student where sage>20;
select count(*) '1999~2002学生人数' from student where (2025-sage) in (1999,2002);
select AVG(grade) '学号为201215122学生平均成绩' from sc where sno = 201215122;
select MAX(grade) 课程号为1的最高成绩 from sc where cno = 1;
select MIN(2025 - sage) 学生最早出生年份 from student ;
--分组查询
select sno 学号,SUM(grade) 每名学生总成绩 from sc group by sno;
select AVG(grade) 每门课程平均成绩 from sc group by cno order by AVG(grade) desc;
select sno 两门以上不及格学生学号 from sc where grade<60 group by sno having count(grade) >= 2;
select sdept 系别,MAX(sage) 各系最大年龄 from student group by sdept;