当前位置:网站首页>Mysql8.0 (summary of new features)

Mysql8.0 (summary of new features)

2022-06-10 19:10:00 Fate friend I


 Insert picture description here

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 :
       Insert picture description here

🧩🧩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 .

 Insert picture description here

I have finished the basic chapter , bye !!!

原网站

版权声明
本文为[Fate friend I]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101815406259.html