0
点赞
收藏
分享

微信扫一扫

mysql外连接和联合查询



文章目录

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

外连接

left join,right join

mysql外连接和联合查询_字段

语法结构:

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)内连接

mysql外连接和联合查询_字段_02

(2)左外连接:

mysql外连接和联合查询_左外连接_03

(3)右外连接:

mysql外连接和联合查询_sql_04

例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 on teacher.tno=teaching.tno left
join sc on teaching.cno=sc.cno
where sc.cno 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 a.cno=“a01” and b.cno=“a02”;



举报

相关推荐

0 条评论