GreatSQL社區原創內容未經授權不得隨意使用,轉載請聯繫小編並註明來源。 GreatSQL是MySQL的國產分支版本,使用上與MySQL一致。 本文來源:原創投稿;作者:YeJinrong/葉金榮 MySQL 8.0.30動態redo log初探 MySQL 8.0.30全新的動態redo lo ...
什麼是WITH AS 語句
WITH AS相當於虛擬視圖。 WITH AS也叫做分解子查詢或者片段子查詢。
定義一個SQL片段, 該片段會被後面的SQL語句用到,可以近似看作一個可用的臨時視圖。
WITH AS優點
增加了SQL的可讀性,如果構造多個片段子查詢,結構會更加清晰。
一次構建,多次使用,達到減少讀的目標。
SYS_TEMP_XXXX便是運行過程中構造的統計結果臨時表。
WITH AS的語法
WITH 臨時視圖名 AS (SELECT查詢)
SELECT .. FROM 臨時視圖名;
-- 單個表臨時視圖
WITH E AS (SELECT * FROM employees)
SELECT * FROM E;
-- 連接多個表的臨時視圖
WITH
e as (SELECT * FROM EMPLOYEES),
d as (SELECT * FROM DEPARTMENTS)
SELECT e.LAST_NAME, d.department_name
FROM e inner join d
ON e.department_id = d.department_id;
-- 聯合多個查詢結果
WITH
e1 as (SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 100),
e2 as (SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 110)
SELECT * from e1
UNION ALL
SELECT * FROM e2;