mysql 高階查詢

2021-08-08 07:57:02 字數 1881 閱讀 5307

####1、巢狀子查詢和相關子查詢

子查詢:

1、乙個詢語句中還包含其他查詢。其中包含其他查詢的查詢叫父查詢,被包含的查詢叫子查詢。

2、子查詢也可以和update、insert、delete一起使用,語法類似於select語句 。

3、子查詢中可以再包含子查詢,即允許多層巢狀。

select * from student where age>(select age from student where stuname=『張巨集』);

巢狀子查詢:非相關子查詢。

1、使用比較運算子的子查詢

###注意:將子查詢和比較運算子聯合使用,必須保證子查詢返回的值不能多於乙個(單值)

select * from student where age>(select age from student where stuname=『張巨集』);

2、使用[not] in 子查詢 範圍子查詢。當子查詢返回多值時,使用這種方式

select * from student where student where stuid in (select stuid from grade where courseid=1);

3、any all 子查詢

#查詢其他系中比資訊系任意乙個學生入學成績低的學生資訊

select stuname,ingrade from student where class<>『資訊系』 and ingrade< any (select max(ingrade) from student where class=『資訊系』);

#查詢其他系中比資訊系所有學生數學成績低的學生資訊

select stuname,ingrade from student where class<>『資訊系』 and ingrade< all (select min(ingrade) from student where class=『資訊系』);

關聯子查詢:exists存在性查詢

####2、通過在子查詢中使用exists子句,可以對子查詢中的行是否存在進行檢查

###使用關聯字查詢 exists ,會對外層用loop逐條查詢,每次查詢都睡去檢視對應的exists語句。

* 非關聯子查詢中子查詢只會執行一次返回結果集

* 關聯子查詢存在性判斷exists中子查詢會重複執行,外層查詢有多少條記錄,內層子查詢就要執行多少次,判斷存在性。

select stuname from student where exists(select 1);

####3、多表聯接查詢

1、內聯接

select s.stuid, s.stuname,g.courseid,g.grade,c.coursename

from student s,grade g,course c

where s.stuid = g.stuid and c.courseid=g.courseid and g.grade>=90

order by g.grade,g.courseid limit 5,5;

2、外聯接

select s.stuid, s.stuname,g.courseid,g.grade

from student s left join grade g

on s.stuid = g.stuid where g.grade>90;

3、自聯接

select e1.empno,e1.mgr,e2.ename from emp e1, emp e2

where e1.mgr = e2.empno;

4、交叉聯接:笛卡爾積

select * from student,grade;
5、使用表的別名

mysql高階查詢in MySQL高階查詢(一)

in 子查詢 巢狀查詢 重點是思路 為什麼要用in?in 在數值上相當於 但是它可以查詢到更多的符合條件的結果,等於號只可以查詢乙個結果 question 有兩種方法 第一種 使用子查詢替換表連線 使用 inner join 將表與表之間聯動,再將實現條件依次寫出來 第二種 採用子查詢 在where...

mysql 高階 查詢 MYSQL中的高階查詢

1.1.子查詢 1.1.1.在房屋型別中,如何找出比雙人間貴的所有房屋型別?找到雙人間的 根據第一步找到的 作為查詢條件去查滿足條件的房屋型別,利用where字句 子查詢是乙個巢狀在 select insert update 或 delete 語句或其他子查詢中的查詢 子查詢在where語句中的一般...

Mysql高階查詢

if expr1,expr2,expr3 如果 expr1 是true 則 if 的返回值為expr2 否則返回值則為 expr3。如 select if status 0 and status promotion 1,1,2 as status from my table ifnull expr1...