MySQL之视图&案例

目录

    • 一.视图
      • 1.1 含义
      • 1.2 操作
    • 二.案例
    • 三.思维导图

一.视图

1.1 含义

虚拟表,和普通表一样使用

1.2 操作

1.创建视图
create view 视图名
as
查询语句;

2.视图的修改
方式一:
create or replace view 视图名
as
查询语句
方式二:
alter view 视图名
as
查询语句

3.删除视图
drop view 视图名,视图名,…;

4.查看视图
DESC 视图名:查看视图相关字段
SHOW CREATE VIEW 视图名:查看视图相关语句

二.案例

01)查询" 01 “课程比” 02 "课程成绩高的学生的信息及课程分数
1.涉及表:t_mysql_student,t_mysql_score
2.链接方式:内链接
3.行转列:流程函数
SELECT
s.*,
(case when t1.cid = ‘01’ then t1.score end) 语文,
(case when t2.cid = ‘02’ then t2.score end) 数学
FROM
t_mysql_student s,
( SELECT * FROM t_mysql_score WHERE cid = ‘01’ ) t1,
( SELECT * FROM t_mysql_score WHERE cid = ‘02’ ) t2
WHERE
s.sid = t1.sid
AND t1.sid = t2.sid
AND t1.score > t2.score
MySQL之视图&案例_第1张图片

02)查询同时存在" 01 “课程和” 02 "课程的情况
SELECT
s.*,
(case when t1.cid = ‘01’ then t1.score end) 语文,
(case when t2.cid = ‘02’ then t2.score end) 数学
FROM
t_mysql_student s,
( SELECT * FROM t_mysql_score WHERE cid = ‘01’ ) t1,
( SELECT * FROM t_mysql_score WHERE cid = ‘02’ ) t2
WHERE
s.sid = t1.sid
AND t1.sid = t2.sid
MySQL之视图&案例_第2张图片

03)查询存在" 01 “课程但可能不存在” 02 "课程的情况(不存在时显示为 null )
SELECT
s.*,
( CASE WHEN t1.cid = ‘01’ THEN t1.score END ) 语文,
( CASE WHEN t2.cid = ‘02’ THEN t2.score END ) 数学
FROM
t_mysql_student s
INNER JOIN ( SELECT * FROM t_mysql_score WHERE cid = ‘01’ ) t1 ON s.sid = t1.sid
LEFT JOIN ( SELECT * FROM t_mysql_score WHERE cid = ‘02’ ) t2 ON t1.sid = t2.sid;
MySQL之视图&案例_第3张图片

04)查询不存在" 01 “课程但存在” 02 "课程的情况
SELECT
s.*,
( CASE WHEN sc.cid = ‘01’ THEN sc.score END ) 语文,
( CASE WHEN sc.cid = ‘02’ THEN sc.score END ) 数学
FROM
t_mysql_student s,
t_mysql_score sc
WHERE
s.sid = sc.sid
AND s.sid NOT IN ( SELECT sid FROM t_mysql_score WHERE cid = ‘01’ )
AND sc.cid = ‘02’
MySQL之视图&案例_第4张图片

05)查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩
考核:聚合函数意味着分组,外链接
SELECT
s.sid,
s.sname,
ROUND( avg( sc.score ), 2 ) 平均成绩
FROM
t_mysql_student s
LEFT JOIN t_mysql_score sc ON s.sid = sc.sid
GROUP BY
s.sid,
s.sname
HAVING
平均成绩 >= 60
MySQL之视图&案例_第5张图片

06)查询在t_mysql_score表存在成绩的学生信息
SELECT
s.sid,
s.sname
FROM
t_mysql_student s
INNER JOIN t_mysql_score sc ON s.sid = sc.sid
GROUP BY
s.sid,
s.sname
MySQL之视图&案例_第6张图片

07)查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null )
SELECT
s.sid,
s.sname,
count( sc.score ) 选课总数,
sum( sc.score ) 总成绩
FROM
t_mysql_student s
LEFT JOIN t_mysql_score sc ON s.sid = sc.sid
GROUP BY
s.sid,
s.sname
MySQL之视图&案例_第7张图片

三.思维导图

MySQL之视图&案例_第8张图片

你可能感兴趣的:(mysql,数据库)