子查詢在實際項目中應用的比較多,也叫嵌套查詢。簡單點說,使用一條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的查詢出來。
修改結果:

