子查询:
语句内部的查询语句就是子查询语句。
用括号括起来,或者保存结果。
场景:
查询代课天数最多的那个老师的信息;
设想1:
Select t_name,gender from teacher_class order by days limit1;
分析:
逻辑上没有问题,但是出现了代课天数一样多的几个老师,
这样就很难处理了,而且还可能会出现相同的老师信息。
设想2:
先获得最多的代课天数是多少,再判断哪个老师的代课天数
和最大值是一样的。
Select max(days) from teacher_class;
Select t_name gender from teacher_class where days=(Select max(days) from teacher_class;);
(mysql 允许将上面的查询结果,作为一个值来使用)
Var1 = Select max(days) from teacher_class;
Select t_name gender from teacher_class where days=var1;
子查询分类:
不同的分类,会有不同的使用方式。
分类标准:
1.子查询插线的位置。
2.子查询的返回值形式。
返回值分类:
单一值(标量),一列,多列,多行多列(表)
使用语法:
标量:获得一个值之后,使用关系运算符,进行判断。
列:获得一列,通常是多行的一列值
场景:获得所有0228班讲师的所有其他带班信息。
设想:先获得0228班讲师的姓名,再通过姓名获取其他班级。
Select t_name from teacher_class where c_name=’php0228’;
Select t_name c_name days from teacher_class where t_namein (Select t_name from teacher_class where c_name=’php0228’);
一定要使用集合类的操作符来完成 :
In|not in.
Any
=any 等同于 in
All
!=all 等同于not in
!=any
2!=any(1,2,3)成立;
! = all
2!=all(1,2,3)不成立;
出现位置:
where型,where后
Exists 型
From型, from后