oracle数据库之子查询

子查询在实际项目中应用的比较多,也叫嵌套查询。简单点说,使用一条sql语句来替代某个值或者某张表,sql:结构化查询,这种方式就是嵌套查询。可能这种说法并不太专业,但是我确实不知道应该怎么说了。。。我们可以通过什么是子查询?了解一下概念。好吧,请原谅我,那么接下来我们可以通过下面的例子看一下啥是子查询?

1.子查询可以替代某个值

--代替某个值
select * from t_class;
select * from t_student;

select * from t_class where classid=1;      -           -查询classid=1的班级信息  
select classid from t_class where classname=706;        -查询classid=1

--嵌套查询实例
select * from t_class where classid=(select classid from t_class where classname=706);  --子查询写法

查询结果:

2. 子查询代替某张表实例:

--代替某张表
select * from t_class;
select * from t_student;

select classid from t_class;  --查询访问id 为123 
select * from t_class where classid in (1,2,3); --显示结果为123的值

select * from t_class where classid in (select classid from t_class );  --子查询写法

查看结果:

3.使用子查询进行修改操作,如下图表所示:

子查询问题1:将sporter表中 的name为张山的运动员的积分修改为 0 分

update  grade set mark = 0 where sporterid=(select sporterid from sporter where name='张山');
commit;

--解题思路:
1.无法通过成绩表直接修改。所以我们需要在另外一张表中进行查询,先将运动员的id查询出来,然后在去修改。

--select sporterid from sporter where name='张山'; --返回的结果是张山对应的sportid

子查询问题2:修改关羽课程1的分数为99 

update t_score
   set score = 99
 where studentid = (select studentid from t_student where name = '关羽')
 and courseid=1;

commit;

--解析:
select studentid from t_student where name = '关羽' and courseid=1; 
--查询关羽课程1对应的学生id

--等价于
update t_score set score = 99 where studentid = 10000;因为关于的id我们无法在分数表中体现所以,需要在另一张表中将满足关羽并且课程id为1的查询出来。

修改结果:

posted @ 2018-02-06 15:22  IT测试老兵  阅读(3886)  评论(0编辑  收藏  举报
作者:测试老兵
出处:https://www.cnblogs.com/fighter007/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。