Window Function是社區版MySQL 8.0為提升查詢分析能力而引入的功能,在PolarDB MySQL版8.0版本中對Window Function進行了全面支援,並可以做並存執行。
前提條件
叢集版本需為PolarDB MySQL版8.0叢集版,且Revision version為8.0.2.2.0或以上,您可以參見查詢版本號碼確認叢集版本。
在Window Function中只有使用了Partition by子句,才可以並存執行查詢。
使用方法
文法:
目前在PolarDB中Window Function只能通過
EXPLAIN FORMAT=TREE
語句來顯示。樣本:
如下樣本中建立了1張表
employee_salaries
,且在表裡插入了一些資料:CREATE TABLE `employee_salaries` ( `dept` varchar(20) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `salary` int DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; INSERT INTO `employee_salaries` VALUES ('Engineering','Dharma',3500), ('Engineering','Bình',3000), ('Engineering','Adalynn',2800), ('Engineering','Samuel',2500), ('Engineering','Cveta',2200), ('Engineering','eve',2000), ('Engineering','Dharma',3500), ('Sales','Carbry',500), ('Sales','Clytemnestra',400), ('Sales','Juraj',300), ('Sales','Kalpana',300), ('Sales','Svantepolk',250), ('Sales','Angelo',200);
如下是
employee_salaries
表的並行查詢計劃:explain format=tree select ROW_NUMBER() OVER(partition by dept order by salary desc) AS 'row_number' from employee_salaries\G *************************** 1. row *************************** EXPLAIN: -> Gather (slice: 1; workers: 4) (cost=26.42 rows=12) -> Window aggregate (cost=15.67 rows=3) -> Repartition (hash keys: employee_salaries.dept; slice: 2; workers: 4) (cost=15.33 rows=3) -> Sort: employee_salaries.dept, employee_salaries.salary DESC (cost=1.55 rows=13) -> Parallel table scan on employee_salaries, with parallel partitions: 4
如上所示,在
employee_salaries
表完成並行掃描後,會將資料按照Partition by子句中指定的key(employee_salaries.dept
)分發到下一階段的Worker中,從而保證Window Function可以完成並行計算且保證結果的正確性,最終在Leader上完成匯總即可。