mysql外连接和联合查询

阅读: 评论:0

mysql外连接和联合查询

mysql外连接和联合查询

文章目录

  • 外连接
      • 左外连接
      • 右外连接
  • 多表连接梳理
  • 联合查询

外连接

left join,right join

语法结构:

select 字段 from 表1 left [out] join 表2 on 表1.关系字段=表2.关系字段; 

左外连接

例1:

select*from a left join b on a.id=b.id;

左外连接的特点:
1、左外连接“左侧表中“中的使用记录都会被展示出来;右侧表中只展示符合条件的记录,不符合条件的记录将会用null值代替;
2、连接方式:
(1)左侧表中符合条件的记录将会与右侧表中符合条件的记录互相连接
(2)左侧表中不符合条件的将会与右侧表中的”空记录”进行连接;

右外连接

例2:

select*from a right join b on a.id=b.id;

右外连接的特点:
1、右外连接”右侧表中”的所有记录都会被展示出来;左侧表中只展示符合条件的记录,不符合条件的记录将会用null值代替;
2、连接方式:
(1)右侧表中符合条件的记录将会与左侧表中符合条件的记录互相连接
(2)右侧表中不符合条件将会与左侧表中的“空记录”进行连接
左外连接和右外连接逻辑相同,意义相对;

多表连接梳理

(1)内连接

(2)左外连接:

(3)右外连接:

例3:查询没有选课的学生的名字;
(1)子查询方法:
(2)左外连接的方法:
练习:查询没有人选的课程名称;(所涉及的表course,sc)
(1)子查询方法:
(2)左外连接的方法:

例4:查询所授课程没有人选的老师名字(teacher,teaching,sc)
查询没有授课的老师的名字;
teacher:包含所有老师的基本信息
teaching:授课任务
sc:包含选修课的情况

子查询的方法:

select tname from teacher where tno in
(select tno from teaching where cno not in(select cno from sc));

teacher,teaching:tno
teahing,sc:cno

内连接结合外连接的写法:

select tname from teacher 
join taching &# left 
join sc on teachingo=sco 
where sco is null;

联合查询

union 和union all
(1)查看union连接的效果
(2)union使用的注意事项:
1、当使用union连接两个子查询时,两个语句拆查询出来的字段数量必须相同,否则无法使用union 进行联合查询;
2、mysql中union和order by、limit联合使用,需要注意的问题:
(1)在union中,在不用括号的情况下,只能用一个order by
(2)limit作用于的是union后的结果集,而不是union后的select语句
错误写法:

select * from student where sname like ‘张%’ order by sname
union
select * from student where sname like ‘’李%‘ order by sname;

例1:查询a01课程成绩最高的前三条记录以及a02课程成绩最高的前三条记录
举例说明:

(select * from sc where cno="a01" order by degree desc limit 3)
union(select * from sc where cno="a02" order by degree desc limit 3)
union(select * from sc where cno="c01" order by degree desc limit 3);

(1)union会过滤掉union两边的select得到的结果集中的重复的行,而union all不会过滤掉重复的行,举例说明;

(select * from sc limit 3)
union(select * from sc limit 3);

例2:查询sc表的前三条记录拼接上sc表的前三条记录;
自连接:属于内连接
自连接:连接是同一张表
from 表名 a,表名 b on a.关系字段=b.关系字段;

自连接什么用:
条件出现在同一个字段;
from sc a,sc b a.sno=b.sno and ao=“a01” and bo=“a02”;

本文发布于:2024-02-04 18:55:15,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170714146358554.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:mysql
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23