当前位置:网站首页>Mysql8.0 (summary of new features)
Mysql8.0 (summary of new features)
2022-06-10 19:10:00 【Fate friend I】
List of articles
- One window function
- 🧣🧣 Two Common table expression

One window function
🪬🪬1.1 Usage and characteristics
What is needed : The results of group statistics are used to calculate each record , Using window functions is better
The characteristic of window function is that it can be grouped , Sort within groups . in addition , The window function will not reduce the number of rows in the original table due to grouping , This is very useful for us to make statistics and sort on the basis of the original table data .
1.2 Window function classification
- Window functions can be divided into Static window function and Dynamic window function .
- The window size of the static window function is fixed , It won't be different because of different records ;
- The window size of dynamic window function will change with different records .
Window functions can be divided into sequence number functions as a whole 、 Distribution function 、 Before and after function 、 Head and tail functions and other functions , The following table :
🧩🧩1.3 Grammatical structure
Syntax structure of window function :
function OVER([PARTITION BY Field name ORDER BY Field name ASC|DESC])
or
function OVER Window name … WINDOW Window name AS ([PARTITION BY Field name ORDER BY Field name ASC|DESC])
- OVER Keyword specifies the scope of the function window .
- If you omit the contents in the following brackets , The window will contain WHERE All records of conditions , The window function will be based on all that meet WHERE The conditions are recorded for calculation .
- If OVER The bracket after the keyword is not empty , You can use the following syntax to set the window . - Window name : Set an alias for the window , Used to identify windows .
- PARTITION BY Clause : Specifies which fields window functions are grouped by . After grouping , The window function can be executed separately in each group .
- ORDER BY Clause : Specifies which fields the window function sorts by . Execute the sorting operation to make the window function number in the order of the sorted data records .
- FRAME Clause : Define rules for a subset of partitions , Can be used as a sliding window .
1.3.1 Ordinal function
1.ROW_NUMBER() function
ROW_NUMBER() The function can display the sequence numbers in the data in order .
- give an example : Inquire about goods The highest price under each commodity category in the data sheet 3 Product information
SELECT *
FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY category_id ORDER BY price DESC) AS row_num,
id, category_id, category, NAME, price, stock
FROM goods) t
WHERE row_num <= 3;
2.RANK() function
Use RANK() Function can sort serial numbers in parallel , And it will skip the repeated serial numbers , For example, the serial number is 1、1、3.
3.DENSE_RANK() function
DENSE_RANK() Function to sort serial numbers in parallel , And won't skip repeated sequence numbers , For example, the serial number is 1、1、2
1.3.2 Distribution function
1.PERCENT_RANK() function
PERCENT_RANK() The function is a percentage function of the rank value . Calculate as follows .
(rank - 1) / (rows - 1)
rank The value of is used RANK() The sequence number generated by the function ,rows The value of is the total number of records in the current window
mysql> SELECT RANK() OVER w AS r,
-> PERCENT_RANK() OVER w AS pr,
-> id, category_id, category, NAME, price, stock
-> FROM goods
-> WHERE category_id = 1 WINDOW w AS (PARTITION BY category_id ORDER BY price
DESC);
+---+-----+----+-------------+---------------+----------+--------+-------+
| r | pr | id | category_id | category | NAME | price | stock |
+---+-----+----+-------------+---------------+----------+--------+-------+
| 1 | 0 | 6 | 1 | Women's wear / Women's Boutique | Woolen coat | 399.90 | 1200 |
| 2 | 0.2 | 3 | 1 | Women's wear / Women's Boutique | fleece | 89.90 | 1500 |
| 2 | 0.2 | 4 | 1 | Women's wear / Women's Boutique | A pair of jeans | 89.90 | 3500 |
| 4 | 0.6 | 2 | 1 | Women's wear / Women's Boutique | dress | 79.90 | 2500 |
| 5 | 0.8 | 1 | 1 | Women's wear / Women's Boutique | T T-shirt | 39.90 | 1000 |
| 6 | 1 | 5 | 1 | Women's wear / Women's Boutique | Pleated skirt | 29.90 | 500 |
+---+-----+----+-------------+---------------+----------+--------+-------+
6 rows in set (0.00 sec)
2.CUME_DIST() function
CUME_DIST() Function is mainly used to query the proportion less than or equal to a value .
SELECT CUME_DIST() OVER(PARTITION BY category_id ORDER BY price ASC) AS cd,
id, category, NAME, price
FROM goods;
1.3.3 Before and after function
1.LAG(expr,n) function
LAG(expr,n) Function returns the first... Of the current line n Yes expr Value .
2.LEAD(expr,n) function
LEAD(expr,n) The function returns the last... Of the current line n Yes expr Value .
1.3.4 Head and tail functions
1.FIRST_VALUE(expr) function
FIRST_VALUE(expr) The function returns the first expr Value .
SELECT id, category, NAME,price,stock,FIRST_VALUE(price) OVER w AS first_price
FROM goods WINDOW w AS (PARTITION BY category_id ORDER BY price);
2.LAST_VALUE(expr) function
LAST_VALUE(expr) The function returns the last expr Value .
1.3.5 Other functions
1. NTH_VALUE(expr,n) function
NTH_VALUE(expr,n) Function returns the second n individual expr Value .
2.NTILE(n) function
NTILE(n) The function divides the ordered data in the partition into n A barrel , Record the bucket number
SELECT NTILE(3) OVER w AS nt,id, category, NAME, price
FROM goods WINDOW w AS (PARTITION BY category_id ORDER BY price);
🧣🧣 Two Common table expression
- Common table expression ( Or universal table expression ) Referred to as CTE(Common Table Expressions).CTE Is a named temporary result set , The scope is the current statement .CTE It can be understood as a reusable sub query , Of course, it is a little different from sub query ,CTE You can quote other CTE, But subqueries cannot reference other subqueries . therefore , Consider replacing subqueries .
- According to the grammatical structure and execution mode , Common table expressions are divided into Common table expressions and Recursive common table expression 2 Kind of .
2.1 Common table expressions
- Grammatical structure :
WITH CTE name
AS ( Subquery )
SELECT|DELETE|UPDATE sentence ;
Common table expressions are similar to subqueries , however , Unlike subqueries , It can be referenced many times , And it can be used by others
Is referenced by a common table expression .
Case study : Query the details of the employee's Department .
mysql> WITH emp_dept_id
-> AS (SELECT DISTINCT department_id FROM employees)
-> SELECT *
-> FROM departments d JOIN emp_dept_id e
-> ON d.department_id = e.department_id;
+---------------+------------------+------------+-------------+---------------+
| department_id | department_name | manager_id | location_id | department_id |
+---------------+------------------+------------+-------------+---------------+
| 90 | Executive | 100 | 1700 | 90 |
| 60 | IT | 103 | 1400 | 60 | |
| 100 | Finance | 108 | 1700 | 100 |
+---------------+------------------+------------+-------------+---------------+
Common table expressions can act as subqueries . In the future, if you need to use sub query , You can check
Before , First define the common table expression , Replace it with a subquery . and , Compared with sub query , Common table expressions are
One advantage , Is the query after defining the common table expression , Common table expressions can be referenced multiple times like a table , Sub query
Can not .
2.2 Recursive common table expression
- Recursive common table expression is also a common table expression , It's just , In addition to the characteristics of common table expressions , It also has its own characteristics , That is, you can call yourself . Its grammatical structure is :
WITH RECURSIVE CTE name
AS ( Subquery )
SELECT|DELETE|UPDATE sentence ;
The recursive common table expression consists of 2 Part of it is made up of , They are seed query and recursive query , Through the keyword in the middle UNION [ALL] Connect .
The seeds here , It means to get the initial value of recursion . This query will only run once , To create the initial dataset , Then recursion
The query is always executed , Until no new query data is generated , Recursively returns .
Cases of burning hands
- Needles are often used for employees surface , contain employee_id,last_name and manager_id Three fields . If a yes b The manager of , that , We can b be called a Subordinates of , If at the same time b again c The manager of , that c Namely b Subordinates of , yes a My subordinates .
- Ideas :
- Use the seed query in the recursive common table expression , Find the first generation of managers . Field n Means generation , The initial value is 1, First generation Manager .
- Use recursive query in recursive common table expression , Find out who is the manager in this recursive common table expression , And the value of generation plus 1. Until no one takes the person in the recursive common table expression as the manager , Recursively returns .
- In the final query , Select all generations greater than or equal to 3 People who , They must be subordinates of the third generation and above , That is, subordinates . So we get the result set we need .
WITH RECURSIVE cte
AS
( SELECT employee_id,last_name,manager_id,1 AS n FROM employees WHERE employee_id = 100
-- Seed query , Find the first generation of leaders
UNION ALL
SELECT a.employee_id,a.last_name,a.manager_id,n+1 FROM employees AS a JOIN cte
ON (a.manager_id = cte.employee_id) -- recursive query , Find people who are led by people who use recursive common table expressions
)
SELECT employee_id,last_name FROM cte WHERE n >= 3;
Recursive common table expressions are useful for querying tree structured data with common root nodes , Very useful . It can be independent of hierarchy
Limit , Easily find out the data of all nodes .
summary : The function of common table expression is to replace sub query , And can be quoted many times . Recursive common table expressions are very efficient for querying tree structured data with a common root node , You can easily handle queries that are difficult to handle by other query methods .

I have finished the basic chapter , bye !!!
边栏推荐
- 3. getting started with golang concurrency
- [kuangbin] topic 12 basic DP1
- 关于YUV格式的一些总结
- 【 random talk 】 congratulations on getting the title of CSDN expert. Your efforts will eventually pay off
- Three ways generated by stream lambda
- 数据治理经典6大痛点?这本书教你解决
- WordPress 6.0 "Arturo Arturo" release
- 单纯形法代码求解(含超详细代码注释和整个流程图)
- Framework and practice of smart city network security construction
- Openssl1.1.1 compilation error can't locate win32/console pm in @INC
猜你喜欢

【 random talk 】 congratulations on getting the title of CSDN expert. Your efforts will eventually pay off

基于ssm在线订餐系统设计与实现.rar(项目源码)

Some summary about YUV format

Cross domain error: when allowcredentials is true, allowedorigins cannot contain the special value "*“

c(指针02)

Low carbon data center construction ideas and future trends

WordPress 6.0 “Arturo阿图罗” 发布

阵列信号处理仿真之四——Z变换分析阵列多项式

In the introductory study of data visualization, we should be alert to pitfalls and misunderstandings and grasp key nodes

How to transform digital transformation? Which way?
随机推荐
lingo12软件下载及lingo语言入门资源
单纯形法代码求解(含超详细代码注释和整个流程图)
HelloWorld example of TestNG and how to run it from the command line
Seata installing the window environment
Adobe Premiere基础-导入导出,合并素材,源文件编译,脱机(二)
The value of Bi in the enterprise: business analysis and development decision
Adobe Premiere Foundation (track related) (V)
WordPress 6.0 “Arturo阿图罗” 发布
JS Touch
Upgrade the playing method of snatching singing, integrate the climax clips of genuine music and real-time scoring ability~
Array type of DB2 SQL pl
最长上升子序列(LIS)洛谷
SPSS入门笔记记录
Adobe Premiere Foundation (animation production - Flexible animation) (VIII)
The question of enterprise managers, where have we spent our money after so many years of informatization?
SQL function
mysql(17-课后练习题)
Cross domain error: when allowcredentials is true, allowedorigins cannot contain the special value "*“
New trends and prospects of data center planning and design under the background of "double carbon"
Ruixin micro rk1126 platform platform porting libevent cross compiling libevent