子查询
1.在select 后边 注意点
1.一定要在两个表之间找好对应关系(teacher.id必须是主键或者必须保证teacher.id在teacher表中是唯一的)
2.子查询中只能有一个字段(子查询的结果必须是一行一列)
使用子查询的时候,建议大家养成使用别名的好习惯,这样可以让我们的查询语句更加清晰。别名可以用来命令新字段,也可以用来命名新表.
select*,(select name from teacher where id=s.teacher id)as'老师姓名'from student as s;
2.在from 后边 注意点
当位于FROM后面时,要注意
1.我们可以把子查询当成一张虚拟的表
2.必须要有别名,因为子查询优先被执行,子查询的别名,可以让别的查询当做表或者列去操作
select *,
case rank
when 'A' then '优'
when 'B' then '良'
when 'C' then '差'
end rank_ch
from (
select *,
case // 不常用的 case when
when score < 60 then 'C'
when score >=60 and score <80 then 'B'
when score >=80 then 'A'
end as rank
from student
) a;
3.在where 后边
注意点
当位于WHERE后面时,要注意
- 多条数据要用in而不要用=,如果确定子查询的结果为一行一列的话,就可以用 = 等于
- 如果返回结果为多行一列的话 要用 in , 一列是必须的,必须是一列
3.子查询中的SELECT后面只能有一个字段(多个字段的话会报错)
多表查询
1.行转列
select name,
随便加个组函数遍历(
case
when course='java'then score
end
)as Java',
min(
case
when course='MySQL'then score
end)
as 'Mysql'from test_9 group by name
select name,score from test_9 group by name
连接查询
内连接: 内连接 inner join
特点:丢失表的特有属性
1、on条件是在生成临时表时使用的条件,需要和链接查询一起使用。
2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。
外连接:
1.left join 保留左表的特有属性, 丢失右表的特有属性
2. right join 保留右表的特有属性, 丢失左表的特有属性