子查询

时间:2021-06-23 16:46:02   收藏:0   阅读:0

一、子查询

二、嵌套子查询

在MySQL中的子查询是可以嵌套使用的,并且可以在一个查询中嵌套任意多个子查询,即一个子查询中还可以包含另一个子查询,这种查询方式为嵌套子查询。

嵌套查询语句格式:

select  列名  from  表名  where  列名  in(select查询语句)

select(select(select(select)

三、相关子查询

指的是子查询的结果有且只有一个值。

(1)使用insert和select语句结合

当insert语句和selecti语句做结合,就是把查询的结果插入到某一张表中。

格式:

insert into表名select查询语句

(2)使用delete和select语句结合

delete from 表名 where 列名 in (select查询语句)

例∶删除计算机系学生的成绩

delete from sc where sno in (select sno from student where dept=’计算机系’)

(3)使用update和select语句(子查询)结合

例如将计算机系全部学生的成绩加5分

Update sc set grade = grade+5

Where sno in (select sno from student where dept=’计算机系’)

四、子查询注意事项

1、where后面的条件要什么,子查询就查什么。比如:条件要学号,子查询就查学号

2、什么情况优先考虑子查询?给出的条件没有明确的提示时候用。例如:查询计算机系学生选修了哪些课程?

3、where后面要用到聚合函数当条件,聚合函数不能直接写,就可以借助查询语句把聚合函数的结果给查出来就行,比如成绩大于平均成绩

where grade>(sellect avg(grade) from sc)==>where grade>78

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!