一、Union
1.Union-表的加法course表course1
在Mysql中将上边两个表加在一起:
SELECT 课程号,课程名称
FROM course
UNION
SELECT 课程号,课程名称
FROM course1两个表格相加,合并重复的部分
运行结果如上,将两个表加在一起了,重复的部分进行了合并,如果想要将两个表的全部数据都展示出来,重复的也展示,则在 union 后边加一个 all 即可。
SELECT 课程号,课程名称
FROM course
UNION ALL
SELECT 课程号,课程名称
FROM course1;所有数据全在(包含重复的部分)
二、Join-表的联结
联结的类型
1.cross join-交叉联结交叉联结
2.inner join-内联结
将学生表和成绩表内联结学生表成绩表
SELECT a.学号,a.姓名,b.课程号
from student AS a INNER JOIN score AS b
ON a.`学号`=b.`学号`;内连接
3.left join-左联结
将学生表和成绩表左联结
SELECT a.学号,a.姓名,b.课程号
from student AS a LEFT JOIN score AS b
ON a.`学号`=b.`学号`;左联结
4.right join-右联结
将学生表和成绩表右联结
SELECT a.学号,a.姓名,b.课程号
from student AS a RIGHT JOIN score AS b
ON a.`学号`=b.`学号`右联结
5.full join-全联结
Mysql不支持全连接
6.sql语句一般结构:
select ........
from.......
where.......
group by......
having .......
order by ......
limit ......
7.sql运行顺序:先运行子查询
每个查询语句里运行顺序
先运行蓝框里的子句
select子句
最后运行红框里的子句
8.练习:
8.1.问题:查询所有学生的学号、姓名、选课数、总成绩
分析:学号、姓名(学生表student)
选课数(每个学生的选课数目:成绩表score,按学号分组,对课程号计数count)
总成绩(每个学生的总成绩:成绩表score,按学号分组,对成绩求和sum)
思路:select 查询结果[学号,姓名,选课数,总成绩]
from 从那张表中查找数据[学生表student,成绩表score;两个表如何联结?通过学号;用哪种联结?左联结]
SELECT a.`学号`,a.`姓名`,COUNT(b.`课程号`),SUM(b.`成绩`)
from student AS a LEFT JOIN score AS b
ON a.`学号`=b.`学号`
GROUP BY a.`学号`;练习1结果
8.2.问题:查询平均成绩大于85的所有学生的学号、姓名和平均成绩
分析:查询出所有学生的学号,姓名,平均成绩
平均成绩>85
SELECT a.`学号`,a.`姓名`,AVG(b.`成绩`)
from student AS a LEFT JOIN score AS b
ON a.`学号`=b.`学号`
GROUP BY a.`学号`
HAVING AVG(b.`成绩`)>85;练习2结果
8.3.问题:查询学生的选课情况
SELECT a.`学号`,a.`姓名`,c.`课程号`,c.`课程名称`
from student AS a INNER JOIN score AS b ON a.`学号`=b.`学号`
INNER JOIN course AS c ON b.`课程号`=c.`课程号`;练习3结果
三、Ase表达式
例子1:查询成绩是否及格
SELECT `学号`,`课程号`,`成绩`,
(CASE WHEN `成绩`>=60 THEN '及格'
WHEN `成绩` <60 THEN '不及格'
ELSE NULL
END)AS '是否及格'
FROM score;例子1结果
例子2:查询及格和不及格人数
SELECT `课程号`,
SUM(CASE WHEN `成绩`>=60 THEN 1 ELSE 0 END) AS '及格人数',
SUM(CASE WHEN `成绩` < 60 THEN 1 ELSE 0 END) AS '不及格人数'
FROM score
GROUP BY `课程号`;例子2结果
例子3:使用分段[100-85],[85-70],[70-60],[<60]来统计各科成绩,分别统计:各分段人数,课程号和课程名称
SELECT a.`课程号`,b.`课程名称`,
SUM(CASE when `成绩` BETWEEN 85 AND 100 THEN 1 ELSE 0 END) AS '[100-85]',
SUM(CASE when `成绩` >=70 AND `成绩` <85 THEN 1 ELSE 0 END) AS '[85-70]',
SUM(CASE when `成绩` >=60 AND `成绩` <70 THEN 1 ELSE 0 END) AS '[70-60]',
SUM(CASE when `成绩` <60 THEN 1 ELSE 0 END) AS '[<60]'
from score as a RIGHT JOIN course as b
ON a.`课程号`=b.`课程号`
GROUP BY a.`课程号`,b.`课程名称`例子3结果
四、sqlzoo-join练习题