mysql筆記(6)-多表查詢之with


本文將簡單介紹with子句的格式和用法

1、目的

通過創建一張(或多張)臨時表,實現數據的抽離,從而方便進行數據的比較

2、格式

//創建2張臨時表,並在這2張臨時表的基礎上進行查詢
with 
temporary_table1_name(column_name,column_name) as 
(select xxx
from xxx),
temporary_table2_name(column_name,column_name) as 
(select xxx
from xxx)
select xxx
from temporary_table1_name,temporary_table2_name;

在上述語句中
temporary_table_name及其后面的column_name 都可以由自己指定

注意:創建的臨時表僅可以用於此次查詢,並不會寫入數據庫的物理內存中

3、實例

6-1.png
在上述的instructor表中,實現以下查詢:
找出 院系總工資 高於 所有院系的平均總工資的 院系名稱

思路如下:
(1)創建臨時表1,使用group by和SUM函數計算各個院系的總工資;
(2)創建臨時表2,對臨時表1的所有行 求平均值,從而得到所有院系的平均總工資;
(3)用常規的select+where語句在2張臨時表的基礎上進行查詢

with 
dept_total(dept_name,value) as
(select dept_name, SUM(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select AVG(salary)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value>=dept_total_avg.value;

結果示意圖如下:
6-2.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM