1. EXISTS子查询
语法
SELECT …… FROM 表名 WHERE EXISTS(子查询);
子查询有返回结果: EXISTS子查询结果为TRUE
子查询无返回结果: EXISTS子查询结果为FALSE,外层查询不执行。
2. NOT EXISTS子查询
SELECT AVG(studentresult)+5 AS 平均分 FROM result WHERE NOT EXISTS ( SELECT * FROM `result` WHERE `subjectNo` = ( SELECT `subjectNo` FROM `subject` WHERE `subjectName` = 'Logic Java' ) AND `examDate` = ( SELECT MAX(`examDate`) FROM `result` WHERE `subjectNo` = ( SELECT `subjectNo` FROM `subject` WHERE `subjectName` = 'Logic Java') ) AND `studentResult` > 60) AND `subjectNo` = ( SELECT `subjectNo` FROM `subject` WHERE `subjectName` = 'Logic Java') AND `examDate` = ( SELECT MAX(`examDate`) FROM `result` WHERE `subjectNo` = ( SELECT `subjectNo` FROM `subject` WHERE `subjectName` = 'Logic Java') );
3. 分组查询用法
语法
SELECT …… FROM <表名> WHERE …… GROUP BY ……
示例
SELECT `subjectNo`,AVG(`studentResult`) AS 课程平均成绩 FROM `result` GROUP BY `subjectNo`;
注意
SELECT列表中只能包含:
1.被分组的列
2.为每个分组返回一个值的表达式,如聚合函数
4. 多列分组
SELECT `gradeId` AS 年级编号,`sex` AS 性别,COUNT(*) AS 人数 FROM `student` GROUP BY `gradeId`,`sex` ORDER BY `gradeId`;
5. 分组筛选
语法
SELECT …… FROM <表名> WHERE …… GROUP BY …… HAVING……
示例
SELECT `subjectNo`,AVG(`studentResult`) AS 课程平均成绩 FROM `result` GROUP BY `subjectNo` HAVING AVG(`studentResult`) >=60;
6. WHERE与HAVING对比
WHERE子句
用来筛选 FROM 子句中指定的操作所产生的行
GROUP BY子句
用来分组 WHERE 子句的输出
HAVING子句
用来从分组的结果中筛选行
7. 内连接
内连接查询的是两张表的关联交集。
语法
SELECT …… FROM 表1 INNER JOIN 表2 ON ……
或者(等值连接)
SELECT …… FROM 表1,表2 WHERE ……
示例
SELECT S.`studentName`,R.`subjectNo`,R.`studentResult` FROM `student` AS S INNER JOIN `result` AS R ON (S.`studentNo` = R.`studentNo`);
SELECT `student`.`studentName`,`result`.`subjectNo`,`result`.`studentResult` FROM `student`,`result` WHERE `student`.`studentNo` = `result`.`studentNo`;
8. 三表内连接
示例
SELECT S.studentName AS 姓名,SU.subjectName AS 课程,R.studentResult AS 成绩 FROM student AS S INNER JOIN `result` AS R ON (S.`studentNo` = R.`studentNo`) INNER JOIN `subject` AS SU ON (SU.subjectNo=R.subjectNo);
9. 左外连接
主表(左表)student中数据逐条匹配表result中的数据
1.匹配,返回到结果集
2.无匹配,NULL值返回到结果集
示例
SELECT S.studentName,R.subjectNo,R.studentResult FROM student AS S LEFT JOIN result AS R ON S.studentNo = R.studentNo;
10. 右外连接
右外连接的原理与左外连接相同
右表逐条去匹配记录;否则NULL填充
SELECT 图书编号,图书名称,出版社名称 FROM 图书表 RIGHT JOIN 出版社表 ON 图书表.出版社编号 = 出版社表.出版社编号;