MySQL——子查詢

什麼是子查詢

  • 在一個查詢之中嵌套了其餘的若干查詢
  • 在where查詢條件中是一個不肯定的值,而是一個來自另外一個查詢的結果。

  • 語句

ex:查詢大於公司平均工資的員工姓名:性能

select avg(sal) from emp;   /* avg(sal)=2000 */
select * from emp where sal >= 2000;
/* 將上面的語句合併 */
select * from emp where sal >= (select avg(sal) from emp);

ex:查詢出工資比anthony還要高的所有僱員信息:spa

select sal from emp where name='anthony'; /* anthony的工資爲10000 */
select * from emp where sal >= 10000;
/* 將上面的語句合併 */
select * from emp where sal >= (select sal from emp where name='anthony');

注意事項

  • 子查詢要用括號括起來
  • 將子查詢放在運算符的右邊(增長可讀性)
  • 對單行子查詢使用單行運算符
  • 對多行子查詢使用多行運算符

子查詢的分類

根據子查詢的結果來劃分的code

單行單列子查詢

  • 返回查詢結果包含一行數據,看做是一個值,使用在where以後
  • 使用單行記錄比較運算符:=; >; <; <=;>=;<>

多行單列子查詢

  • 返回查詢結果可能多行或者零行,看做是多個值,使用在where以後
  • 使用多行比較運算符:

IN

與返回列表中的任意一個值相等
ex:查詢工資等於部門經理的員工信息圖片

select sal from emp where job ='manager';  /* 先查詢部門經理的工資 */

圖片描述

ANY

與返回的任意一個值比較it

  • =ANY:此時和in操做同樣
  • >ANY:大於子查詢中最小的值
  • <ANY:小於子查詢中最大的值

ALL

與返回的值每個值比較io

  • >ALL:大於查詢中最大的值
  • <ALL:小於查詢中最小的值

多列子查詢

  • 返回查詢結果的結構是單行或多行,看做是一張臨時表,使用在from以後
  • 性能:笛卡爾積的數量
select d.deptno,d.dname,temp.c,temp.a
from dept d join 
 (select deptno,count(empno) c,avg(sal) a from emp group by deptno) temp        
on using(deptno);

union/union all

join用於把表橫向鏈接,union/union all用於把表縱向鏈接
注意:class

  • union內部的select語句必須擁有相同數量的列

-列也必須擁有兼容的數據類型select

  • 每條select語句中的列的順序必須相同
  • union結果集中的列名老是等於union中第一個select語句中的列名
  • union操做符選取不一樣的值,若是容許重複的值,使用union all(性能高)
select empno,ename,dname from emp left join dept using(deptno)
union 
select empno,ename,dname from emp right join dept using(deptno);
相關文章
相關標籤/搜索