WITH as語法
#WITH as語法主要分為以下兩個部分:
#1)WITH :關鍵字,用於引入一個或多個臨時表。
2)AS:關鍵字,用來定義一個或多個暫存表。
WITH as語句的一般語法如下:
WITH [RECURSIVE] cte_name (column_name1,column_name2,...) AS ( subquery1 UNION [ALL] subquery2 UNION [ALL] subquery3 ... ) SELECT * FROM cte_name;
其中,
cte_name:臨時表的名稱;
column_name1,column_name2,...:臨時表中的列名;
subquery1、subquery2、subquery3...:子查詢語句。
WITH as實際應用
WITH as語句的實際應用場景主要包括以下幾個面向:
##1)遞歸查詢透過使用WITH語句,可實現遞歸查詢並獲得一個具有層次結構的結果集。以下以一個員工表為例來進行說明:WITH RECURSIVE emp AS ( SELECT emp_id, emp_name, emp_manager_id FROM employees WHERE emp_manager_id IS NULL UNION ALL SELECT e2.emp_id, e2.emp_name, e2.emp_manager_id FROM employees e2 INNER JOIN emp ON e2.emp_manager_id = emp.emp_id ) SELECT * FROM emp;
WITH sales AS ( SELECT p.product_id, p.product_name, s.sale_id, s.sale_date, s.quantity, s.price FROM products p INNER JOIN sales s ON p.product_id = s.product_id ), inventory AS ( SELECT p.product_id, p.product_name, i.inventory_id, i.quantity FROM products p INNER JOIN inventory i ON p.product_id = i.product_id ) SELECT s.sale_id, s.sale_date, s.product_id, s.product_name, s.quantity, s.price, i.inventory_id, i.quantity as inventory_quantity FROM sales s INNER JOIN inventory i ON s.product_id = i.product_id;
WITH ord AS ( SELECT order_id FROM orders WHERE order_date > '2022-01-01' ) SELECT * FROM order_details WHERE order_id IN (SELECT order_id FROM ord);
以上是with as mysql語法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!