当前位置:网站首页>MySQL Foundation

MySQL Foundation

2022-06-23 05:35:00 ThXe

The problem of importing tables

Foreign key constraints when importing data

Data import instruction :

source d:\xxx.sql

adopt FOREIGN_KEY_CHECKS solve , Usage is as follows :

set FOREIGN_KEY_CHECKS=0;  # Set to do not check foreign key constraints before import 
set FOREIGN_KEY_CHECKS=1;  # Resume checking foreign key constraints after import 

The third chapter _ The most basic SELECT sentence

1. SQL Rules and norms of language

1) The basic rule

  • SQL It can be written on one or more lines . To improve readability , Write each clause separately , Use indent if necessary
  • Every order is made with ; or \g or \G end
  • Keywords cannot be abbreviated or separated
  • About punctuation
    • All must be guaranteed ()、 Single quotation marks 、 Double quotes end in pairs
    • Half angle input mode in English must be used
    • Single quotation marks can be used for string and date time data (’ ') Express
    • Alias of column , Try to use double quotes (" "), And it is not recommended to omit as

2) SQL Case specification ( It is recommended that )

  • MySQL stay Windows The environment is case insensitive
  • MySQL stay Linux The environment is case sensitive
    • Database name 、 Table name 、 The table alias 、 Variable names are strictly case sensitive
    • keyword 、 Function name 、 Name ( Or field name )、 Alias of column ( The alias of the field ) It's case insensitive .
  • A unified writing standard is recommended :
    • Database name 、 Table name 、 Table alias 、 Field name 、 Fields, aliases, etc. are all lowercase
    • SQL keyword 、 Function name 、 Bound variables, etc., are all capitalized

3) notes

 Single-line comments :# Note text (MySQL In a particular way )
 Single-line comments :--  Note text (-- Must be followed by a space .)
 Multiline comment :/*  Note text  */

4) Naming rules

  • database 、 The table name must not exceed 30 Characters , Variable names are limited to 29 individual
  • Must contain only A–Z, a–z, 0–9, _ common 63 Characters
  • Database name 、 Table name 、 Do not include spaces in object names such as field names The same MySQL In software , The database cannot have the same name ; In the same library , A watch cannot have the same name ;
  • In the same table , The field cannot have the same name You must ensure that your field has no and reserved words 、 Database systems or common methods conflict . If you insist on using , Please be there. SQL In a sentence, make use `( mark of emphasis ) Lead up
  • Keep field names and types consistent , When naming fields and specifying data types for them, be sure to ensure consistency . If data Type is an integer in a table , Then don't turn into character in another table

2. Basic SELECT sentence

1) SELECT … FROM

  • grammar
SELECT  Identifies which columns to select 
FROM  Identifies which table to choose from 
  • Select all columns
SELECT *
FROM departments;
  • Select a specific column :
SELECT department_id, location_id
FROM departments;

2) Alias of column

  • Rename a column
  • Easy to calculate
  • Keep up with the column name , You can also add keywords between column names and aliases AS, Aliases use double quotes , To include spaces or special characters in the alias Special characters and case sensitive .
  • AS It can be omitted
  • It is recommended that aliases be short , See the name and know the meaning
  • give an example :
SELECT last_name AS name, commission_pct comm
FROM employees;

3) Remove duplicate lines

DISTINCT keyword

SELECT DISTINCT department_id FROM employees;

4) Null values participate in the operation

Null value :null ( Not equal to 0, ’ ‘, ’null‘ )

Solutions to practical problems : introduce IFNULL

SELECT employee_id, salary " Monthly wages ", salary * (1 + IFNULL(commission_pct, 0)) * 12 " Annual wage " FROM employees;

Here you must pay attention to , stay MySQL Inside , A null value is not equal to an empty string . The length of an empty string is 0, And the length of a null value Degree is empty . and , stay MySQL Inside , Null values take up space .

5) mark of emphasis ``

You must ensure that your field has no and reserved words 、 Database system or common method conflicts .

If you insist on using , stay SQL Use in statement ` ` Lead up .

SELECT * FROM `order`;

6) Query constant

SELECT ' Xiao Zhang Technology ' as " Company name ", employee_id, last_name FROM employees;

3. Display table structure

Displays the details of the fields in the table

DESCRIBE employees;
 or 
DESC employees;
mysql> desc employees;
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| employee_id | int(6) | NO | PRI | 0 | |
| first_name | varchar(20) | YES | | NULL | |
| last_name | varchar(25) | NO | | NULL | |
| email | varchar(25) | NO | UNI | NULL | |
| phone_number | varchar(20) | YES | | NULL | |
| hire_date | date | NO | | NULL | |
| job_id | varchar(10) | NO | MUL | NULL | |
| salary | double(8,2) | YES | | NULL | |
| commission_pct | double(2,2) | YES | | NULL | |
| manager_id | int(6) | YES | MUL | NULL | |
| department_id | int(4) | YES | MUL | NULL | |
+----------------+-------------+------+-----+---------+-------+
11 rows in set (0.00 sec)

among , The meanings of each field are explained as follows :

  • Field: Field name .
  • Type: Represents the field type , here barcode、goodsname It's textual ,price It's of type integer .
  • Null: Indicates whether the column can store NULL value .
  • Key: Indicates whether the column is indexed .
  • PRI Indicates that the column is part of the table primary key ;
  • UNI Indicates that the column is UNIQUE Part of the index part ;
  • MUL Indicates that a given value is allowed to appear more than once in a column .
  • Default: Indicates whether the column has a default value , If there is , So what's the value .
  • Extra: Represents additional information about a given column that can be obtained , for example AUTO_INCREMENT etc. .

4. Filtering data

  • grammar :
SELECT  Field 1, Field 2
FROM  Table name 
WHERE  Filter conditions 

Use WHERE Clause , Filter out rows that do not meet the criteria .WHERE Clause in the wake of FROM Clause .

  • give an example :
SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90;

Chapter four _ Operator

DUAL False watch

1. Arithmetic operator

SELECT 100 + 0, 100 + 50 * 30, 100 - 35.5 FROM DUAL;
  • An integer type value adds and subtracts integers , The result is still an integer ;
  • An integer type value adds and subtracts floating-point numbers , The result is a floating point number ;
  • stay Java in , + If there is a string on the left and right sides of , Then it represents the splicing of strings . But in MySQL in + It only means that the values are added . If a non numeric type is encountered , First try to convert to a value , If the transfer fails , Just press the 0 Calculation .( notes :MySQL String functions are used in string splicing CONCAT() Realization )
  • In mathematics ,0 Cannot be used as a divisor , stay MySQL in , A number divided by 0 by NULL.

2. Comparison operator

1) The equal sign operator

The comparison operator is used to compare the operands on the left and right of the expression , If the comparison result is true, it returns 1, The result of the comparison If false, return 0, Other cases return to NULL.

Comparison operators are often used as SELECT Use the conditions of the query statement , Return qualified result records .

If the values on both sides of the equal sign 、 One of the strings or expressions is NULL, The comparison result is NULL.

mysql> SELECT 1 = 1, 1 = '1', 1 = 0, 'a' = 'a', (5 + 3) = (2 + 6), '' = NULL , NULL = NULL;
+-------+---------+-------+-----------+-------------------+-----------+-------------+
| 1 = 1 | 1 = '1' | 1 = 0 | 'a' = 'a' | (5 + 3) = (2 + 6) | '' = NULL | NULL = NULL |
+-------+---------+-------+-----------+-------------------+-----------+-------------+
|   1   |    1    |   0   |     1     |          1        |    NULL   |     NULL    |
+-------+---------+-------+-----------+-------------------+-----------+-------------+
1 row in set (0.00 sec)
mysql> SELECT 1 = 2, 0 = 'abc', 1 = 'abc' FROM DUAL;
+-------+-----------+-----------+
| 1 = 2 | 0 = 'abc' | 1 = 'abc' |
+-------+-----------+-----------+
|   0   |     1     |     0     |
+-------+-----------+-----------+
1 row in set, 2 warnings (0.00 sec)
  • If the values on both sides of the equal sign 、 The string or expression is a string , be MySQL Will compare by string , Its comparative Is the number of characters in each string ANSI Whether the codes are equal .
  • If the values on both sides of the equal sign are integers , be MySQL The size of the two values will be compared according to integers .
  • If the value on both sides of the equal sign is an integer , The other is the string , be MySQL Will convert strings to numbers for comparison .
  • If the values on both sides of the equal sign 、 One of the strings or expressions is NULL, The comparison result is NULL.
ysql> SELECT 1 <=> '1', 1 <=> 0, 'a' <=> 'a', (5 + 3) <=> (2 + 6), '' <=> NULL,NULL <=> NULL FROM dual;
+-----------+---------+-------------+---------------------+-------------+---------------+
| 1 <=> '1' | 1 <=> 0 | 'a' <=> 'a' | (5 + 3) <=> (2 + 6) | '' <=> NULL | NULL <=> NULL |
+-----------+---------+-------------+---------------------+-------------+---------------+
|     1     |    0    |      1      |           1         |      0      |       1       |
+-----------+---------+-------------+---------------------+-------------+---------------+
1 row in set (0.00 sec)

You can see , When using the safe equals operator , The values of the operands on both sides are NULL when , The result returned is 1 instead of NULL, Other returned results are the same as the equal operator .

2) Not equal to the operator

Not equal to the operator (<> and !=) Used to judge the numbers on both sides 、 Whether the values of strings or expressions are not equal , Returns if not equal 1, Equal returns 0. Not equal to operator cannot judge NULL value . If either of the values on both sides is NULL, Or on both sides NULL, The result is NULL. SQL Examples of statements are as follows :

mysql> SELECT 1 <> 1, 1 != 2, 'a' != 'b', (3+4) <> (2+6), 'a' != NULL, NULL <> NULL;
+--------+--------+------------+----------------+-------------+--------------+
| 1 <> 1 | 1 != 2 | 'a' != 'b' | (3+4) <> (2+6) | 'a' != NULL | NULL <> NULL |
+--------+--------+------------+----------------+-------------+--------------+
|    0   |    1   |      1     |        1       |     NULL    |      NULL    |
+--------+--------+------------+----------------+-------------+--------------+
1 row in set (0.00 sec)

Besides , There are also non symbolic operators :

image-20220531154418141

3) Air transport operator

Air transport operator (IS NULL perhaps ISNULL) Determines whether a value is NULL, If NULL Then return to 1, Otherwise return to 0.

mysql> SELECT NULL IS NULL, ISNULL(NULL), ISNULL('a'), 1 IS NULL;
+--------------+--------------+-------------+-----------+
| NULL IS NULL | ISNULL(NULL) | ISNULL('a') | 1 IS NULL |
+--------------+--------------+-------------+-----------+
|      1       |       1      |      0      |     0     |
+--------------+--------------+-------------+-----------+
1 row in set (0.00 sec)

4) Non air transport operators

Non air transport operators (IS NOT NULL) Judge whether a value is not NULL, If not for NULL Then return to 1, Otherwise return to 0.

5) Minimum operator

The grammar format is :LEAST( value 1, value 2,…, value n). among ,“ value n” Indicates that there is... In the parameter list n It's worth . There is In the case of two or more parameters , Return minimum .

mysql> SELECT LEAST (1,0,2), LEAST('b','a','c'), LEAST(1,NULL,2);
+---------------+--------------------+-----------------+
| LEAST (1,0,2) | LEAST('b','a','c') | LEAST(1,NULL,2) |
+---------------+--------------------+-----------------+
|       0       |          a         |        NULL     |
+---------------+--------------------+-----------------+
1 row in set (0.00 sec)

As can be seen from the results , When the parameter is an integer or floating point number ,LEAST Will return the smallest value ; When the parameter is a string , Return word The first character in the parent table ; When there is... In the comparison value list NULL when , Cannot judge size , The return value is NULL.

6) Maximum operator

The grammar format is :GREATEST( value 1, value 2,…, value n). among ,n Indicates that there is... In the parameter list n It's worth . When there is When two or more parameters , The return value is the maximum value . If any of the independent variables is NULL, be GREATEST() The return value of is NULL.

mysql> SELECT GREATEST(1,0,2), GREATEST('b','a','c'), GREATEST(1,NULL,2);
+-----------------+-----------------------+--------------------+
| GREATEST(1,0,2) | GREATEST('b','a','c') | GREATEST(1,NULL,2) |
+-----------------+-----------------------+--------------------+
|         2       |             c         |         NULL       |
+-----------------+-----------------------+--------------------+
1 row in set (0.00 sec)

As can be seen from the results , When the parameter is an integer or floating point number ,GREATEST Will return the largest value ; When the parameter is a string , Returns the last character in the alphabet ; When there is... In the comparison value list NULL when , Cannot judge size , The return value is NULL.

7) BETWEEN AND Operator

BETWEEN The format used by the operator is usually SELECT D FROM TABLE WHERE C BETWEEN A AND B, here , When C Greater than or equal to A, also C Less than or equal to B when , The result is 1, Otherwise, the result is 0.

8) IN Operator

IN Operator is used to determine whether a given value is IN A value in the list , If so, return 1, Otherwise return to 0. If The fixed value is NULL, perhaps IN List exists NULL, The result is NULL.

mysql> SELECT 'a' IN ('a','b','c'), 1 IN (2,3), NULL IN ('a','b'), 'a' IN ('a', NULL);
+----------------------+------------+-------------------+--------------------+
| 'a' IN ('a','b','c') | 1 IN (2,3) | NULL IN ('a','b') | 'a' IN ('a', NULL) |
+----------------------+------------+-------------------+--------------------+
|            1         |      0     |         NULL      |          1         |
+----------------------+------------+-------------------+--------------------+

9) NOT IN Operator

NOT IN Operator is used to determine whether a given value is not IN A value in the list , If not IN One in the list It's worth , Then return to 1, Otherwise return to 0.

10) LIKE Operator

LIKE Operators are mainly used to match strings , Usually used for fuzzy matching , If the condition is met, return 1, Otherwise return to 0. If the given value or matching condition is NULL, Then the returned result is NULL.

“%”: matching 0 Characters or more .
“_”: Only one character can be matched .

11) ESCAPE

Avoiding special symbols : Use escape characters . for example : take [%] To [ %]、[] To [ ], And then add [ESCAPE‘$’] that will do .

SELECT job_id
FROM jobs
WHERE job_id LIKE ‘IT\_%‘;

If you use \ To signify an escape , Omit ESCAPE. If not \, Then add ESCAPE.

SELECT job_id
FROM jobs
WHERE job_id LIKE ‘IT$_%‘ escape ‘$‘;

12) REGEXP Operator

REGEXP Operators are used to match strings , The grammar format is : expr REGEXP Matching condition .

(1)‘^’ Matches a string that begins with the character after the character .

(2)‘$’ Matches a string that ends with a character that precedes the character .

(3)‘.’ Match any single character .

(4)“[…]” Match any character in square brackets . for example ,“[abc]” matching “a” or “b” or “c”. To name the range of characters , Use one individual ‘-’.“[a-z]” Match any letter , and “[0-9]” Match any number .

(5)‘’ Match zero or more characters before it . for example ,“x” Match any number of ‘x’ character ,“[0-9]” Match any number of numbers , and “” Match any number of any characters .

3. Logical operators

Logical operators are mainly used to judge whether an expression is true or false , stay MySQL in , The return result of the logical operator is 1、0 perhaps NULL.

MySQL Chinese support 4 The logical operators are as follows :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-cza54bhz-1655907404971)(MySQL The basic chapter .assets/image-20220531195405333.png)]

4. An operation

Bit operators are operators that evaluate on binary numbers . Bit operators first convert operands to binary numbers , And then we do bit operations , Finally, the calculation result is changed from binary to decimal .

MySQL The supported bitwise operators are as follows :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-22Ak4SdS-1655907404972)(MySQL The basic chapter .assets/image-20220531195442995.png)]

5. Operator precedence

The larger the number , The higher the priority , Operators with higher priority are calculated first .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-rV9w1Ccy-1655907404973)(MySQL The basic chapter .assets/image-20220531195522668.png)]

Expand : Using regular expression queries

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-PoPbIGPh-1655907404973)(MySQL The basic chapter .assets/image-20220531204253508.png)]

The fifth chapter _ Sorting and paging

1. Sort rule

  • Use ORDER BY Clause ordering

    • ASC(ascend): Ascending
    • DESC(descend): Descending
  • ORDER BY Clause in SELECT End of statement .

1) Single column sort

SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date;

2) Multi column sorting

  • Can be used not in SELECT Sort the columns in the list .
  • When sorting multiple columns , The first column sorted first must have the same column value , Will sort the second column . If the first All values in a column of data are unique , The second column will no longer be sorted .

2. Pagination

  • Format :
LIMIT [ Position offset ,]  Row number 
  • give an example :
-- front 10 Bar record :
SELECT * FROM  Table name  LIMIT 0,10;
 perhaps 
SELECT * FROM  Table name  LIMIT 10;
-- The first 11 to 20 Bar record :
SELECT * FROM  Table name  LIMIT 10,10;
-- The first 21 to 30 Bar record :
SELECT * FROM  Table name  LIMIT 20,10;

MySQL 8.0 Can be used in “LIMIT 3 OFFSET 4”, It means to get from 5 A record starts after 3 Bar record , and “LIMIT 4,3;” The results returned are the same .

  • Paging explicit formula :( The current number of pages -1)* Number of entries per page , Number of entries per page
SELECT * FROM table
LIMIT(PageNo - 1) * PageSize, PageSize;
  • Be careful :LIMIT Clause must be placed throughout SELECT At the end of the sentence !

  • Use LIMIT The benefits of

The number of results returned by the constraint can Reduce the network transmission of data tables , It's fine too Improve query efficiency . If we know that the return result is only 1 strip , You can use LIMIT 1 , tell SELECT Statement only needs to return a record . The good thing is SELECT No need To scan a complete table , You only need to retrieve a qualified record to return .

Chapter six _ Multi-table query

1. Multi table query classification explanation

1) Self join

subject : Inquire about employees surface , return < staff works for Boss >

SELECT CONCAT(worker.last_name , ' works for ', manager.last_name)
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id;

2) Internal connection and external connection

  • Internal connection : Merging rows of more than two tables with the same column , There are no rows in the result set that do not match one table with another

SQL92 grammar

SELECT emp.employee_id, dep.department_name
FROM employee emp, department dep
WHERE emp.`department_id` = dep.`department_id`;

SQL99 grammar

SELECT emp.employee_id, dep.department_name
FROM employee emp JOIN department dep
ON emp.`department_id` = dep.`department_id`;
  • External connection : In addition to the rows that meet the connection conditions, the two tables also return the left ( Or right ) The table does not meet the conditions That's ok , This connection is called left ( Or right ) External connection . When there are no matching rows , The corresponding column in the result table is empty (NULL).
  • If it's a left outer connection , The table on the left of the join condition is also called Main table , The table on the right is called From the table .

LEFT OUTER JOIN

SELECT last_name, department_name
FROM employees emp LEFT OUTER JOIN department dep
ON emp.`department_id` = dep.`department_id`;
  • If it's a right outer connection , The table on the right in the join condition is also called Main table , The table on the left is called From the table .

RIGHT OUTER JOIN

SELECT last_name, department_name
FROM employees emp RIGHT OUTER JOIN department dep
ON emp.`department_id` = dep.`department_id`;

2. UNION Use

Merge query results

utilize UNION keyword , You can give more than one SELECT sentence , And combine their results into a single result set . Merge when , The number of columns and data types of the two tables must be the same , And correspond to each other . each SELECT Use... Between statements UNION or UNION ALL Keyword separation .

Grammar format :

SELECT column,... FROM table1
UNION [ALL]
SELECT column,... FROM table2

UNION The operator

UNION Operator returns the union of the result sets of two queries , Remove duplicate records .

UNION ALL The operator

UNION ALL Operator returns the union of the result sets of two queries . For duplicate parts of two result sets , No weight removal .

Be careful : perform UNION ALL Statement requires more resources than UNION Few statements . If you know clearly that there is no duplicate data in the result data after data consolidation , Or you don't need to remove duplicate data , Try to use UNION ALL sentence , To improve the efficiency of data query .

give an example : Check department number >90 Or the mailbox contains a Employee information

# The way 1
SELECT * FROM employees WHERE email LIKE '%a%' OR department_id>90;
# The way 2
SELECT * FROM employees WHERE email LIKE '%a%'
UNION
SELECT * FROM employees WHERE department_id>90;

give an example : Query the information of men in Chinese users and middle-aged men in American users

SELECT id,cname FROM t_chinamale WHERE csex=' male '
UNION ALL
SELECT id,tname FROM t_usmale WHERE tGender='male';

3. Seven kinds SQL JOINS The implementation of the

image-20220531224324213
#  Chinese : Internal connection 
SELECT employee_id,department_name
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`;

#  Top left : The left outer join 
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`;

#  Top right : Right connection 
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`;

#  Middle left :
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL;

#  Middle right :
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;


#  Bottom left : Full outer join 
#  The way 1: Top left  UNION ALL  Middle right 
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;


#  The way 2: Middle left  UNION ALL  Top right 
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`;

#  Bottom right : Middle left   UNION ALL  Middle right 
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;

4. SQL99 The new features of grammar

1) Natural join

SQL99 stay SQL92 Provides some special syntax based on , such as NATURAL JOIN Used to represent natural connections . We can Natural connection is understood as SQL92 The equivalent connection in . It will help you automatically query the two connection tables All the same fields , Then proceed equivalence Connect .

stay SQL92 In the standard :

SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`
AND e.`manager_id` = d.`manager_id`;

stay SQL99 You can write :

SELECT employee_id,last_name,department_name
FROM employees e NATURAL JOIN departments d;

2) USING Connect

When we connect ,SQL99 Also supports the use of USING Specify... In the data table Fields with the same name Make an equivalent connection . But only with close JOIN Use it together . such as :

SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
USING (department_id);

You can see the connection with nature NATURAL JOIN The difference is ,USING Specifies the specific same field name , You need to USING The brackets of () Fill in the field with the same name to be specified . Use at the same time JOIN…USING Can be simplified JOIN ON Equivalent connection . It and the next Face SQL The query results are the same :

SELECT employee_id,last_name,department_name
FROM employees e ,departments d
WHERE e.department_id = d.department_id;

5. Summary

There are three ways to constrain table joins :WHERE, ON, USING

  • WHERE: Applicable to all associated queries
  • ON : And the only JOIN Use it together , Only association conditions can be written . Although Association conditions can be combined to WHERE Together with other conditions Write , But it's better to write separately .
  • USING: And the only JOIN Use it together , Moreover, the names of the two associated fields should be consistent in the associated table , And can only represent Related words Equal value segment

We need to control the number of connection tables .

Multiple table join is equivalent to nesting for The cycle is the same , Very resource intensive , Will make SQL Query performance It's very bad , So don't join unnecessary tables .

In many DBMS in , There will also be a limit on the maximum connection table .

#  Exercise consolidation 
#  Be careful : After two off table connections , Form a master table and a slave table , The connection field of the main table is not empty , The join field from the table may be empty , Therefore, the key fields of the table are used to determine whether it is empty .

# 1. Query which departments have no employees 
#  Mode one 
SELECT d.department_id
FROM departments d LEFT JOIN employees e
ON d.`department_id` = e.`department_id`
WHERE e.`department_id` IS NULL;

#  Mode two 
SELECT department_id
FROM departments d
WHERE NOT EXISTS (
		SELECT *
    	FROM employees e
    	WHERE e.`department_id` = d.`department_id`
);

# 2. Find out which city has no department 
SELECT l.location_id, l.city
FROM locations l LEFT JOIN departments d
ON l.`location_id` = d.`location_id`
WHERE d.`location_id` IS NULL;

# 3. Query department name is  Sales  or  IT  Employee information 
SELECT e.employee_id, e.last_name, e.department_id
FROM employees e JOIN department d
ON e.`department_id` = d.`department_id`
WHERE d.`department_name` IN ('Sales', 'IT');

Chapter vii. _ One line function

1. Numerical function

1) Basic functions

function usage
ABS(x) return x The absolute value of
SIGN(X) Cell
PI() Returns the value of the pi
CEIL(x),CEILING(x) Returns the smallest integer greater than or equal to a value
FLOOR(x) Returns the largest integer less than or equal to a value
LEAST(e1,e2,e3…) Returns the minimum value in the list
GREATEST(e1,e2,e3…) Returns the maximum value in the list
MOD(x,y) return X Divide Y Remainder after
RAND() return 0~1 The random value
RAND(x) return 0~1 The random value , among x The value of is used as the seed value , same X Values produce the same random Count
ROUND(x) Returns a pair x After rounding the value of , Closest to X The integer of
ROUND(x,y) Returns a pair x The value of is rounded to the nearest X Value , And keep it after the decimal point Y position
TRUNCATE(x,y) Return to digital x Truncated to y The result of decimal places
SQRT(x) return x The square root of . When X When the value of is negative , return NULL

2) Angle and radian exchange function

function usage
RADIANS(x) Convert angles to radians , among , Parameters x Is the angle value
DEGREES(x) Convert radians to angles , among , Parameters x Is the radian value

3) Trigonometric functions

function usage
SIN(x) Convert angles to radians , among , Parameters x Is the angle value
ASIN(x) Convert radians to angles , among , Parameters x Is the radian value
COS(x) return x Cosine of , among , Parameters x Is the radian value
ACOS(x) return x The arccosine of , That is, get the cosine as x Value . If x The value of is not in -1 To 1 Between , Then return to NULL
TAN(x) return x The tangent of , among , Parameters x Is the radian value
ATAN(x) return x The arctangent of , That is, the tangent value returned is x Value
ATAN2(m,n) Returns the arctangent of two parameters
COT(x) return x Cotangent of , among ,X Is the radian value

4) Exponential and logarithmic functions

function usage
POW(x,y),POWER(X,Y) return x Of y Power
EXP(X) return e Of X Power , among e It's a constant ,2.718281828459045
LN(X),LOG(X) Return to e At the bottom of the X The logarithmic , When X <= 0 when , The result returned is NULL
LOG10(X) Return to 10 At the bottom of the X The logarithmic , When X <= 0 when , The result returned is NULL
LOG2(X) Return to 2 At the bottom of the X The logarithmic , When X <= 0 when , return NULL

5) Conversion between bases

function usage
BIN(x) return x Binary code of
HEX(x) return x Hexadecimal encoding
OCT(x) return x Octal encoding
CONV(x,f1,f2) return f1 The base number becomes f2 Hexadecimal number

2. String function

function usage
ASCII(S) Return string S Of the first character in ASCII Code value
CHAR_LENGTH(s) Return string s The number of characters . The functions and CHARACTER_LENGTH(s) identical
LENGTH(s) Return string s Bytes of , It's about character sets
CONCAT(s1,s2,…,sn) Connect s1,s2,…,sn For a string
CONCAT_WS(x, s1,s2,…,sn) Same as CONCAT(s1,s2,…) function , But add... Between each string x
INSERT(str, idx, len, replacestr) The string str From idx Position start ,len Substrings of characters long are replaced with strings replacestr
REPLACE(str, a, b) Use string b Replace string str All the strings that appear in a
UPPER(s) or UCASE(s) The string s All the letters of are converted to capital letters
LOWER(s) or LCASE(s) The string s All the letters of are converted to lowercase letters
LEFT(str,n) Return string str The leftmost n Characters
RIGHT(str,n) Return string str Far right n Characters
LPAD(str, len, pad) Use string pad Yes str Fill on the far left , until str The length of is len Characters
RPAD(str ,len, pad) Use string pad Yes str Fill on the far right , until str The length of is len Characters
LTRIM(s) Remove string s The space on the left
RTRIM(s) Remove string s The space on the right
TRIM(s) Remove string s Start and end spaces
TRIM(s1 FROM s) Remove string s The beginning and the end s1
TRIM(LEADING s1 FROM s) Remove string s At the beginning s1
TRIM(TRAILING s1 FROM s) Remove string s At the end s1
REPEAT(str, n) return str repeat n Results of
SPACE(n) return n A space
STRCMP(s1,s2) Compare strings s1,s2 Of ASCII The size of the code value
SUBSTR(s,index,len) Return from string s Of index Position it len Characters , The functions and SUBSTRING(s,n,len)、 MID(s,n,len) identical
LOCATE(substr,str) Return string substr In string str The first place in , Act on POSITION(substr IN str)、INSTR(str,substr) identical . Not found , return 0
ELT(m,s1,s2,…,sn) Returns the string at the specified location , If m=1, Then return to s1, If m=2, Then return to s2, If m=n, Then return to sn
FIELD(s,s1,s2,…,sn) Return string s The position of the first occurrence in the string list
FIND_IN_SET(s1,s2) Return string s1 In string s2 Where in . among , character string s2 Is a comma separated string
REVERSE(s) return s The inverted string
NULLIF(value1,value2) Compare two strings , If value1 And value2 equal , Then return to NULL, Otherwise return to value1

Be careful :MySQL in , The position of the string is from 1 At the beginning .

3. Date and time functions

1) Get date 、 Time

function usage
CURDATE() ,CURRENT_DATE() Return current date , Only years 、 month 、 Japan
CURTIME() , CURRENT_TIME() Return current time , When only 、 branch 、 second
NOW() / SYSDATE() / CURRENT_TIMESTAMP() / LOCALTIME() / LOCALTIMESTAMP() Returns the current system date and time
UTC_DATE() return UTC( World standard time ) date
UTC_TIME() return UTC( World standard time ) Time

2) Date and time stamp conversion

function usage
UNIX_TIMESTAMP() With UNIX Returns the current time in the form of a timestamp .SELECT UNIX_TIMESTAMP() - >1634348884
UNIX_TIMESTAMP(date) Time date With UNIX Return in the form of a timestamp .
FROM_UNIXTIME(timestamp) take UNIX The time of the timestamp is converted to the time of the normal format

3) Get month 、 week 、 Weeks 、 Functions such as days

function usage
YEAR(date) / MONTH(date) / DAY(date) Return the specific date value
HOUR(time) / MINUTE(time) / SECOND(time) Return specific time value
FROM_UNIXTIME(timestamp) take UNIX The time of the timestamp is converted to the time of the normal format
MONTHNAME(date) Return to the month :January,…
DAYNAME(date) Day of the week :MONDAY,TUESDAY…SUNDAY
WEEKDAY(date) What day of the week , Be careful , Zhou 1 yes 0, Zhou 2 yes 1,... Sunday is 6
QUARTER(date) Returns the quarter corresponding to the date , The scope is 1~4
WEEK(date) , WEEKOFYEAR(date) Go back to the week of the year
DAYOFYEAR(date) The return date is the day of the year
DAYOFMONTH(date) The return date is the day of the month
DAYOFWEEK(date) What day of the week , Be careful : Sunday is 1, Monday is 2,... Saturday is 7

4) Operation function of date

function usage
EXTRACT(type FROM date) Returns a specific part of a specified date ,type Specifies the value to be returned

EXTRACT(type FROM date) Function type The value and meaning of :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-EEIP8V6c-1655907404974)(MySQL The basic chapter .assets/image-20220601162705975.png)]

5) Time and second conversion function

function usage
TIME_TO_SEC(time) take time Convert to seconds and return the result value . The conversion formula is : Hours *3600+ minute *60+ second
SEC_TO_TIME(seconds) take seconds The description is converted to include hours 、 Minutes and seconds

6) A function that calculates the date and time

function usage
DATE_ADD(datetime, INTERVAL expr type), ADDDATE(date,INTERVAL expr type) Returns the difference between the given date and time INTERVAL Date time of the time period
DATE_SUB(date,INTERVAL expr type), SUBDATE(date,INTERVAL expr type) Return and date Difference between INTERVAL The date of the interval

In the above functions type The value of :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-1AXwmUML-1655907404975)(MySQL The basic chapter .assets/image-20220601165055639.png)]

function usage
ADDTIME(time1,time2) return time1 add time2 Time for . When time2 When it is a number , It stands for second , Can be negative
SUBTIME(time1,time2) return time1 subtract time2 After time . When time2 When it is a number , Representative yes second , Can be negative
DATEDIFF(date1,date2) return date1 - date2 Number of days between dates
TIMEDIFF(time1, time2) return time1 - time2 Time interval of
FROM_DAYS(N) Return from 0000 year 1 month 1 The date of ,N Days later
TO_DAYS(date) Return date date distance 0000 year 1 month 1 Days of the day
LAST_DAY(date) return date The date of the last day of the month
MAKEDATE(year,n) Returns a date for a given year and the number of days in the year
MAKETIME(hour,minute,second) Set the given hour 、 Minutes and seconds are combined into time and return
PERIOD_ADD(time,n) return time add n After time

7) Formatting and parsing of dates

function usage
DATE_FORMAT(date,fmt) According to the string fmt Format date date value
TIME_FORMAT(time,fmt) According to the string fmt Format time time value
GET_FORMAT(date_type,format_type) Returns the display format of the date string
STR_TO_DATE(str, fmt) According to the string fmt Yes str To analyze , Resolve to a date

Above Not GET_FORMAT Function fmt Common format characters for parameters :

Format symbol explain Format symbol explain
%Y4 The number of digits indicates the year %y Two digits for the year
%M The name of the month means the month (January,…)%m Two figures indicate the month (01,02,03...)
%b Abbreviated month name (Jan.,Feb.,…)%c The number represents the month (1,2,3,…)
%D The English suffix indicates the number of days in the month (1st,2nd,3rd,…)%d Two figures indicate the number of days in the month (01,02…)
%e The number of days in the month (1,2,3,4,5…)
%H Two figures represent decimals ,24 hourly (01,02…)%h and %I Two figures represent hours ,12 hourly (01,02…)
%k Hours in digital form ,24 hourly (1,2,3)%l The number represents the hour ,12 hourly (1,2,3,4…)
%i Two figures represent minutes (00,01,02)%S and %s Two digits are seconds (00,01,02…)
%W The name of the week of the week (Sunday…)%a The abbreviation of a week (Sun., Mon.,Tues.,…)
%w Number the days of the week (0=Sunday,1=Monday…)
%j With 3 The number of digits represents the number of days in the year (001,002…)%U Number the week of the year , (1,2,3..) among Sunday For the first time of the week God
%u Number the week of the year , (1,2,3..) among Monday For the first time of the week God
%T24 hourly %r12 hourly
%pAM or PM%% Express %

4. Process control functions

Process processing functions can be based on different conditions , Perform different processes , Can be in SQL Statement to implement different conditional choices . MySQL The process processing functions in mainly include IF()、IFNULL() and CASE() function .

function usage
IF(value,value1,value2) If value The value of is TRUE, return value1, Otherwise return to value2
IFNULL(value1, value2) If value1 Not for NULL, return value1, Otherwise return to value2
CASE WHEN Conditions 1 THEN result 1 WHEN Conditions 2 THEN result 2 … [ELSE resultn] END amount to Java Of if…else if…else…
CASE expr WHEN Constant values 1 THEN value 1 WHEN Constant values 1 THEN value 1 … [ELSE value n] END amount to Java Of switch…case…

5. Encryption and decryption functions

The encryption and decryption function is mainly used to encrypt and decrypt the data in the database , To prevent data from being stolen by others . These functions are very useful in ensuring database security .

function usage
PASSWORD(str) Return string str The encrypted version of ,41 Bit long string . The encryption result is irreversible , Commonly used for user password encryption
MD5(str) Return string str Of md5 Encrypted value , It's also a form of encryption . If the parameter is NULL, Will return NULL
SHA(str) From the original plaintext password str Calculate and return the encrypted password string , When the parameter is NULL when , return NULL. SHA Encryption algorithm than MD5 More secure .
ENCODE(value,password_seed) Return to use password_seed Encrypt as an encryption password value
DECODE(value,password_seed) Return to use password_seed Decrypt as an encrypted password value

6. MySQL Information functions

MySQL There are some built-in functions that can be queried MySQL Functions of information , These functions are mainly used to help database developers or operation and maintenance personnel better understand Maintain the database .

function usage
VERSION() Returns the current MySQL Version number of
CONNECTION_ID() Returns the current MySQL Number of connections to the server
DATABASE(),SCHEMA() return MySQL The database where the command line is currently located
USER(),CURRENT_USER()、SYSTEM_USER(), SESSION_USER() Return to the current connection MySQL Username , The format of the returned result is “ Host name @ user name ”
CHARSET(value) Return string value The character set of the argument
COLLATION(value) Return string value Comparison rules of

MySQL There are some functions in that cannot be specifically classified , But these functions are MySQL In the process of development, operation and maintenance of Of .

function usage
FORMAT(value,n) Returns a pair of numbers value Formatted result data .n Express rounding Keep it later After the decimal point n position
CONV(value,from,to) take value The value of is converted between different hexadecimals
INET_ATON(ipvalue) Will be separated by dots IP The address is converted to a number
INET_NTOA(value) Put... In digital form IP The address is converted to dot separated IP Address
BENCHMARK(n,expr) Expression expr repeat n Time . Used for testing MySQL Handle expr The cost of the expression Time for
CONVERT(value USING char_code) take value The character encoding used is modified to char_code

Chapter viii. _ Aggregate functions

1. Aggregate function introduction

  • What are aggregate functions

Aggregate functions act on a set of data , And return a value for a set of data .

  • Aggregate function type
    • AVG()
    • SUM()
    • MAX()
    • MIN()
    • COUNT()

1) AVG and SUM function

SELECT AVG(salary), MAX(salary),MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';

2) MIN and MAX function

You can use... For any data type MIN and MAX function .

SELECT MIN(hire_date), MAX(hire_date)
FROM employees;

3) COUNT function

COUNT(*) Returns the total number of records in the table , Applicable to any data type .

SELECT COUNT(*)
FROM employees
WHERE department_id = 50;

COUNT(expr) return expr Total number of records that are not empty .

SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 50;
  • problem : use count(*),count(1),count( Name ) Who's good ?

Actually , about MyISAM There's no difference between the engine's tables . There is a counter inside the engine that maintains the number of rows . Innodb The watch of the engine count(*),count(1) Read lines directly , Complexity is O(n), because innodb I really have to count it . But good Specific count( Name ).

  • problem : Can I use count( Name ) Replace count(*)?

Do not use count( Name ) To replace count() , count() yes SQL92 The syntax for defining the number of standard statistics lines , Heel count Database independent , Follow NULL He Fei NULL irrelevant . explain :count(*) The statistical value is NULL The line of , and count( Name ) This column is not counted NULL Row of values .

2. GROUP BY

1) Basic use

have access to GROUP BY Clause divides the data in a table into groups

SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

Conclusion 1:SELECT The fields of non group functions appearing in must be declared in GROUP BY in .

​ conversely ,GROUP BY Fields declared in can not appear in SELECT in .

Conclusion 2:GROUP BY The statement in FROM Back 、WHERE Back 、ORDER BY front 、LIMIT front .

2) Use WITH ROLLUP

SELECT department_id,AVG(salary)
FROM employees
WHERE department_id > 80
GROUP BY department_id WITH ROLLUP;

Be careful : When using ROLLUP when , Can't be used at the same time ORDER BY Clause to sort the results , namely ROLLUP and ORDER BY Are mutually exclusive .

3. HAVING

1) Basic use

Filter grouping :HAVING Clause

  1. Rows have been grouped .
  2. The aggregate function is used .
  3. Satisfy HAVING The grouping of conditions in the clause will be displayed .
  4. HAVING Not to be used alone , Must follow GROUP BY Use it together .
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 ;

requirement

  • If an aggregate function is used in the filter condition , Must be used HAVING To replace WHERE. otherwise , Report errors .
  • When there is no aggregate function in the filter condition , Then the secondary filter condition is declared in WHERE Medium or HAVING Either way . however , Recommendation statement at WHERE High execution efficiency in .
  • HAVING It must be stated that in GROUP BY Behind
  • In development , We use HAVING The premise is SQL Used in GROUP BY.

2) WHERE and HAVING Comparison of

difference 1:WHERE You can directly use the fields in the table as filter criteria , However, you cannot use the calculation function in the group as the filter condition ; HAVING Must be with GROUP BY In combination with , You can use the grouping calculation function and grouping field as the filter criteria .

To determine the , When it is necessary to make grouping statistics on data ,HAVING Can finish WHERE Tasks that cannot be completed . This is because , In the query syntax structure ,WHERE stay GROUP BY Before , Therefore, the grouping results cannot be filtered .HAVING stay GROUP BY And after , You can use group fields and calculation functions in groups , Filter the grouped result set , This function is WHERE Unable to complete Of . in addition ,WHERE Excluded records are no longer included in the group .

difference 2: If you need to obtain the required data from the associated table through connection ,WHERE Filter first and then connect , and HAVING Connect first Post screening .

This point , This determines that in the association query ,WHERE Than HAVING More efficient . because WHERE You can screen first , Use one Connect smaller filtered datasets with associated tables , This takes up less resources , The implementation efficiency is also relatively high .HAVING You need to First prepare the result set , That is, association with unfiltered data sets , Then filter the large data set , This takes up There are more resources , Execution efficiency is also low .

The summary is as follows :

keyword usage shortcoming
WHERE Filter the data before associating , High execution efficiency You cannot filter using the calculation function in the group
HAVING You can use the calculation function in the group Filter in the final result set , Low execution efficiency

Choices in development :

WHERE and HAVING It's not mutually exclusive , We can use both in one query WHERE and HAVING. Include groups The condition of statistical function is HAVING, For ordinary conditions WHERE. such , We're taking advantage of WHERE Efficient and rapid of conditions , Again Waved HAVING You can use the advantages of query conditions that include grouping statistics functions . When the amount of data is very large , The operation efficiency will be very Big difference .

4. SELECT Implementation process of

1) The structure of the query

# The way 1:
SELECT ...,....,...
FROM ...,...,....
WHERE  Connection conditions of multiple tables 
AND  Filter conditions that do not contain group functions 
GROUP BY ...,...
HAVING  Contains filter conditions for group functions 
ORDER BY ... ASC/DESC
LIMIT ...,...
# The way 2:
SELECT ...,....,...
FROM ... JOIN ...
ON  Connection conditions of multiple tables 
JOIN ...
ON ...
WHERE  Filter conditions that do not contain group functions 
AND/OR  Filter conditions that do not contain group functions 
GROUP BY ...,...
HAVING  Contains filter conditions for group functions 
ORDER BY ... ASC/DESC
LIMIT ...,...
# among :
#(1)from: From which tables to filter 
#(2)on: When associating multiple table queries , Remove Cartesian product 
#(3)where: Conditions filtered from the table 
#(4)group by: Group by 
#(5)having: Sift through the statistical results again 
#(6)order by: Sort 
#(7)limit: Pagination 

Need to remember SELECT Two order of query :

1. The order of keywords cannot be reversed :

SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT...

1. SELECT The order in which statements are executed ( stay MySQL and Oracle in ,SELECT The execution sequence is basically the same ):

FROM -> WHERE -> GROUP BY -> HAVING -> SELECT  Field of  -> DISTINCT -> ORDER BY -> LIMIT

For example, you wrote a SQL sentence , Then its keyword order and execution order are as follows :

SELECT DISTINCT player_id, player_name, count(*) as num #  The order  5
FROM player JOIN team ON player.team_id = team.team_id #  The order  1
WHERE height > 1.80 #  The order  2
GROUP BY player.team_id #  The order  3
HAVING num > 2 #  The order  4
ORDER BY num DESC #  The order  6
LIMIT 2 #  The order  7

stay SELECT When the statement executes these steps , Each step produces a Virtual table , Then pass the virtual table to the next step Step as input . It should be noted that , These steps are implicit in SQL During the execution of , It's invisible to us .

2) SQL Implementation principle of

SELECT It's to execute first FROM This step of . At this stage , If multiple tables are used for associated query , The following steps will be followed :

  1. First pass CROSS JOIN Find the Cartesian product , Equivalent to getting a virtual table vt(virtual table)1-1;
  2. adopt ON Screening , In virtual tables vt1-1 On the basis of , Get the virtual table vt1-2;
  3. Add external row . If we use the left connection 、 Right link or full link , It will involve external lines , That is, in virtual surface vt1-2 Add external rows based on , Get the virtual table vt1-3.
  • Of course, if we operate more than two tables , The above steps will be repeated , Until all tables are processed . This process has to It's our raw data .

  • Then go to step 3 and step 4 , That is to say GROUP and HAVING Stage . At this stage , It's actually in the virtual table vt2 Of Group and group filtering based on , Get the middle virtual table vt3 and vt4 .

  • When we have finished the condition screening section , You can filter the fields extracted from the table , That is to say, to enter SELECT and DISTINCT Stage .

  • First, in the SELECT The phase will extract the desired fields , And then in DISTINCT Stage filters out duplicate rows , Get the middle virtual table vt5-1 and vt5-2 .

  • When we extract the desired field data , You can sort according to the specified fields , That is to say ORDER BY Stage , obtain Virtual table vt6 .

  • Last in vt6 On the basis of , Take out the record of the specified line , That is to say LIMIT Stage , Get the final result , The corresponding virtual table vt7 .

  • Of course we're writing SELECT At the time of statement , Not all keywords exist , The corresponding stage will be omitted .

Also because SQL It is a structured query language similar to English , So we're writing SELECT At the time of statement , Also pay attention to the corresponding Keyword order , The so-called principle of bottom operation , That's the execution sequence we just talked about .

Chapter nine _ Subquery

1. Basic use

  • The basic syntax structure of subquery :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BxiH00DW-1655907404976)(MySQL The basic chapter .assets/image-20220603133759153.png)]

  • Subquery ( Internal query ) Execute once before the main query .
  • The results of the sub query are by the main query ( External query ) Use .
  • matters needing attention
    • Subqueries should be enclosed in parentheses
    • Place the subquery to the right of the comparison criteria
    • Single line operators correspond to single line subqueries , Multiline operators correspond to multiline subqueries

2. Classification of subqueries

Classification 1:

We return one or more records according to the results of internal query , Sub queries are divided into Single line sub query 、 Multi line sub query .

  • Single line sub query

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-BFEwhvZX-1655907404976)(MySQL The basic chapter .assets/image-20220603135507360.png)]

  • Multi line sub query

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-fq7HueXt-1655907404977)(MySQL The basic chapter .assets/image-20220603135544144.png)]

Classification 2:

We check whether the query is executed more than once , Divide the subquery into relevant ( Or associated ) Subquery and Unrelated ( Or unrelated ) Subquery .

The subquery queries the data results from the data table , If this data result is executed only once , The data result is then executed as a condition of the main query , Then such a subquery is called an unrelated subquery .

Again , If the subquery needs to be executed multiple times , That is, in the form of circulation , Start with an external query , Every time a subquery is passed in to query , The results are then fed back to the outside world , This nested execution is called related subquery .

3. Single line sub query

1) Single line comparison operator

The operator meaning
=equal to
>greater than
>=greater than or equal to
<less than
<=less than or equal to
<>not equal to

2) Code example

  • subject : return job_id And 141 Same as employee No ,salary Than 143 The name of the employee with a large number of employees ,job_id And wages
SELECT last_name, job_id, salary
FROM eployees
WHERE job_id = (
	SELECT job_id
	FROM eployees
    WHERE employee_id = 141
)
AND salary > (
	SELECT salary
	FROM eployees
    WHERE employee_id = 143
);
  • subject : Query and 141 Number or 174 Of employee No manager_id and department_id Of the same other employees employee_id, manager_id,department_id
#  Implementation mode I : Unpaired comparison 
SELECT employee_id, manager_id, department_id
FROM employees
WHERE manager_id IN
        (SELECT manager_id
        FROM employees
        WHERE employee_id IN (174,141))
AND department_id IN
        (SELECT department_id
        FROM employees
        WHERE employee_id IN (174,141))
AND employee_id NOT IN(174,141);

#  Implementation mode II : Compare in pairs 
SELECT employee_id, manager_id, department_id
FROM employees
WHERE (manager_id, department_id) IN
        (SELECT manager_id, department_id
        FROM employees
        WHERE employee_id IN (141,174))
AND employee_id NOT IN (141,174);
  • subject : The minimum wage is greater than 50 The Department of minimum wage id And its minimum wage
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id
HAVING MIN(salary) >
            (SELECT MIN(salary)
            FROM employees
            WHERE department_id = 50);

3) CASE Subqueries in

subject : Explicit employee employee_id,last_name and location. among , If employee department_id And location_id by 1800 Of department_id identical , be location by ’Canada’, The rest are ’USA’.

SELECT employee_id, last_name,
    (CASE department_id
    WHEN
        (SELECT department_id FROM departments
        WHERE location_id = 1800)
    THEN 'Canada' ELSE 'USA' END) location
FROM employees;

4) Null value problem in subquery

SELECT last_name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Haas');

The subquery does not return any rows

5) Illegal use of subquery

SELECT employee_id, last_name
FROM employees
WHERE salary =
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);

Multi line subqueries use single line comparators

4. Multi line sub query

  • Also known as set comparison subquery
  • Inner query returns multiple rows
  • Use the multiline comparison operator

1) Multiline comparison operator

The operator meaning
IN Equal to any one of the list
ANY It needs to be used with the single line comparison operator , Compare with a value returned by a subquery
ALL It needs to be used with the single line comparison operator , Compare with all the values returned by the subquery
SOME It's actually ANY Another name for , The same effect , Commonly used ANY

2) Code example

  • subject : Return to other job_id Middle ratio job_id by ‘IT_PROG’ Employee number of any low paid employee in the Department 、 full name 、job_id as well as salary
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE job_id <> 'IT_PROG' 
AND salary < ANY(
	SELECT salary
    FROM emplyees
    WHERE job_id = 'IT_PROG'
);
  • subject : Query the Department with the lowest average wage id
# The way 1:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(salary) = (
        SELECT MIN(avg_sal)
        FROM (
            SELECT AVG(salary) avg_sal
            FROM employees
            GROUP BY department_id
            ) dept_avg_sal
);
# The way 2:
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(salary) <= ALL (
        SELECT AVG(salary) avg_sal
        FROM employees
        GROUP BY department_id
);

3) The null problem

SELECT last_name
FROM employees
WHERE employee_id NOT IN (
    SELECT manager_id
    FROM employees
    WHERE manager_id IS NOT NULL
);

5. Correlation subquery

If the execution of a subquery depends on an external query , Usually, it is because the tables in the subquery use external tables , And the conditions are analyzed relation , So every time you execute an external query , All subqueries have to be recalculated , Such a subquery is called Associated subquery .

Related sub queries are executed row by row , Each row of the main query executes a subquery .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nKoNqcN1-1655907404978)(MySQL The basic chapter .assets/image-20220603154919387.png)]

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-no7zGEb4-1655907404978)(MySQL The basic chapter .assets/image-20220603155013864.png)]

explain : The columns in the main query are used in the subquery

1) Code example

  • subject : Query the salary of employees whose salary is greater than the average salary of the Department last_name,salary And its department_id
#  Mode one : Use related subqueries 
SELECT last_name, salary, department
FROM employees e1
WHERE salary > (
		SELECT AVG(salary)
    	FROM employees e2
    	WHERE department_id = e1.`department_id`
);
#  Mode two : stay FROM Zhongshengmingzi query 
SELECT e.last_name, e.salary, e.department_id
FROM employees e, (
    			SELECT department_id, AVG(salary) avg_sal
    			FROM employees
    			GROUP BY department_id) t_dept_avg_salary
WHERE e.department_id = t_dept_avg_salary.department_id
AND e.salary > t_dept_avg_salary.avg_sal;

stay ORDER BY Use subqueries in :

  • Check the employee's id,salary, according to department_name Sort
SELECT employee_id, salary
FROM employees e
ORDER BY (
	SELECT department_name
    FROM departments d
    WHERE e.`department_id` = d.`department_id`
);
  • subject : if employees In the table employee_id And job_history In the table employee_id The same number is not less than 2, Output these same id Of our employees employee_id,last_name And its job_id
SELECT e.employee_id, last_name,e.job_id
FROM employees e
WHERE 2 <= (SELECT COUNT(*)
        FROM job_history
        WHERE employee_id = e.employee_id
);

2) EXISTS And NOT EXISTS keyword

  • Associated subqueries are usually associated with EXISTS Operators are used together , Used to check whether there are qualified rows in the sub query .
  • If there are no qualified rows in the subquery :
    • Conditional return FALSE
    • Continue to find... In subqueries
  • If there are qualified rows in the subquery :
    • Do not continue to find in subquery
    • Conditional return TRUE
  • NOT EXISTS Keyword means that if there is no condition , Then return to TRUE, Otherwise return to FALSE.

subject : Query company managers employee_id,last_name,job_id,department_id Information

#  Mode one :EXISTS
SELECT employee_id, last_name, job_id, department_id
FROM employees e1
WHERE EXISTS ( SELECT *
        FROM employees e2
        WHERE e2.manager_id =
        e1.employee_id
);

#  Mode two : Self join 
SELECT DISTINCT e1.employee_id, e1.last_name, e1.job_id, e1.department_id
FROM employees e1 JOIN employees e2
ON e1.employee_id = e2.manager_id;

#  Mode three :IN
SELECT employee_id, last_name, job_id, department_id
WHERE employee_id IN (
        SELECT DISTINCT manager_id
        FROM employees
);

subject : Inquire about departments In the table , There is no in employees Of the departments in the table department_id and department_name

#  Mode one :
SELECT d.department_id, d.department_name
FROM departments e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL;

#  Mode two :
SELECT department_id, department_name
FROM departments d
WHERE NOT EXISTS (
	SELECT *
    FROM employees e
    WHERE d.`department_id` = e.`department_id`
);

3) Related updates

UPDATE table1 alias1
SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);

Use related subqueries to update data from one table to another .

subject : stay employees Add one department_name Field , The data is the Department name corresponding to the employee

# 1)
ALTER TABLE employees
ADD(department_name VARCHAR2(14));

# 2)
UPDATE employees e
SET department_name = (SELECT department_name
FROM departments d
WHERE e.department_id = d.department_id);

4) Relevant delete

DELETE FROM table1 alias1
WHERE column operator (SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);

Use related subqueries to delete data from one table based on data from another .

subject : Delete table employees in , And emp_history Data from all tables

DELETE FROM employees e
WHERE employee_id in(
    SELECT employee_id
    FROM emp_history
    WHERE employee_id = e.employee_id
);

6. Thinking questions

problem : Whose pay ratio is Abel The height of ? answer :

# The way 1: Self join 
SELECT e2.last_name,e2.salary
FROM employees e1,employees e2
WHERE e1.last_name = 'Abel'
AND e1.`salary` < e2.`salary`;
# The way 2: Subquery 
SELECT last_name,salary
FROM employees
WHERE salary > (
    SELECT salary
    FROM employees
    WHERE last_name = 'Abel'
);

problem : Are the above two methods good or bad ?

answer : Good self connection mode !

Subqueries can be used in the title , You can also use self connection . In general, it is recommended that you use self connection , Because in many DBMS I've dealt with it Cheng Zhong , The processing speed of self join is much faster than sub query . It can be understood in this way : Sub query is actually the condition judgment after query through unknown table , The self connection is through the known self data table Make condition judgment , So in most cases DBMS Self join processing has been optimized in .

7. Practice after class

  1. Query and Zlotkey Name and salary of employees in the same department
SELECT last_name, salary
FROM employees
WHERE department_id = (
	SELECT department_id
    FROM employees
    WHERE last_name = 'Zlotkey'
);
  1. Query the employee number of the employee whose salary is higher than the average salary of the company , Name and salary .
SELECT employee_id, last_name, salary
FROM employees
WHERE salary > (
	SELECT AVG(salary)
    FROM employee
);
  1. Select salary greater than all JOB_ID = ‘SA_MAN’ The salary of the employee last_name, job_id, salary
SELECT last_name, job_id, salary
FROM employees
WHERE salary > ALL (
	SELECT salary
    FROM employees
    WHERE job_id = 'SA_MAN'
);
  1. Queries and names contain letters u Employee number and name of employees in the same department
SELECT employee_id, last_name
FROM eployees
WHERE department_id IN (
    SELECT DISTINCT department_id
    FROM employees
    WHERE last_name LIKE '%u%'
);
  1. Check the... In the Department location_id by 1700 The employee number of the employee working in the Department
SELECT employee_id
FROM employees
WHERE department_id IN (
	SELECT department_id
    FROM departments
    WHERE location_id = 1700
);
  1. The query manager is King The name and salary of the employee
SELECT last_name, salary
FROM employees
WHERE manage_id IN (
	SELECT employee_id
    FROM employees
    WHERE last_name = 'King'
);
  1. Query the lowest paid employee information (last_name, salary)
SELECT last_name, salary
FROM employees
WHERE salary = (
	SELECT MIN(salary)
    FROM employees
);
  1. Search the Department with the lowest average wage
#  Mode one 
SELECT *
FROM departments
WHERE department_id = (
	SELECT department_id
    FROM employees
    GROUP BY department_id
    HAVING AVG(salary) = (
    	SELECT MIN(avg_sal)
        FROM (
        	SELECT AVG(salary) avg_sal
            FROM employees
            GROUP BY department_id
        ) t_dept_avg_sal
    )
);

#  Mode two 
SELECT *
FROM departments
WHERE department_id = (
	SELECT department_id
    FROM employees
    GROUP BY department_id
    HAVING AVG(salary) <= ALL (
        SELECT AVG(salary) avg_sal
        FROM employees
        GROUP BY department_id
    )
);

#  Mode three : LIMIT
SELECT *
FROM departments
WHERE department_id IN (
    SELECT department_id
    FROM employees
    GROUP BY department_id
    HAVING AVG(salary) = (
    	SELECT AVG(salary) avg_sal
        FROM employees
        GROUP BY department_id
        ORDER BY avg_sal ASC
        LIMIT 1
    )
);

#  Mode 4 
SELECT d.*
FROM departments d, (
	SELECT department_id, AVG(salary) avg_sal
    FROM employees
    GROUP BY department_id
    ORDER BY avg_sal ASC
    LIMIT 0,1
) t_dept_avg_sal
WHERE d.`department_id` = t_dept_avg_sal.`department_id`;
  1. Query the information of the Department with the lowest average wage and the average wage of the Department ( Correlation subquery )
SELECT d.*, (SELECT AVG(salary) FROM employees WHERE department_id = d.`department_id`) avg_sal
FROM departments d, (
	SELECT department_id, AVG(salary) avg_sal
    FROM employees
    GROUP BY department_id
    ORDER BY avg_sal ASC
    LIMIT 0,1
) t_dept_avg_sal
WHERE d.`department_id` = t_dept_avg_sal.`department_id`;
  1. Find the highest average wage job Information
SELECT *
FROM jobs
WHERE job_id = (
	SELECT job_id
    FROM employees
    GROUP BY job_id
    HAVING AVG(salary) = (
    	SELECT MAX(avg_sal)
        FROM (
        	SELECT AVG(salary) avg_sal
            FROM employees
            GROUP BY job_id
        ) t_job_avg_sal
    )
);
  1. Query the departments whose average salary is higher than the average salary of the company ?
SELECT depatment_id
FROM employees
WHERE department_id IS NOT NULL
GROUP BY department_id
HAVING AVG(salary) > (
	SELECT AVG(salary)
    FROM eployees
);
  1. Find out all the manager Details of
#  The way 1: Self join 
SELECT DISTINCT *
FROM employees emp, employees manager
WHERE emp.`manager_id` = manager.`employee_id`;

SELECT DISTINCT *
FROM employees emp JOIN employees manager
ON emp.`manager_id` = manager.`employee_id`; 

#  The way 2: Subquery 
SELECT *
FROM employees
WHERE employee_id IN (
	SELECT manager_id
    FROM employees
);

#  The way 3:EXISTS
SELECT *
FROM employees manager
WHERE EXISTS (
	SELECT *
    FROM employees emp
    WHERE manager.`employee_id` = emp.`manager_id`
);
  1. In all departments , What is the minimum wage of the lowest department in the highest wage ?
#  Mode one :
SELECT MIN(salary)
FROM employees
WHERE department_id = (
    SELECT department_id
    FROM employees
	GROUP BY department_id
	HAVING MAX(salary) = (
    	SELECT MIN(max_sal)
        FROM (
        	SELECT MAX(salary) max_sal
            FROM employees
            GROUP BY department_id
        ) t_dept_max_sal
    ) 
);

#  Mode two :
SELECT MIN(salary)
FROM employees
WHERE department_id = (
    SELECT department_id
    FROM employees
	GROUP BY department_id
	HAVING MAX(salary) <= ALL (
        SELECT MAX(salary)
        FROM employees
        GROUP BY department_id
    ) 
);

#  Mode three :
SELECT MIN(salary)
FROM employees
WHERE department_id = (
    SELECT department_id
    FROM employees
	GROUP BY department_id
	HAVING MAX(salary) = (
        SELECT MAX(salary) max_sal
        FROM employees
        GROUP BY department_id
        ORDER BY max_sal ASC
        LIMIT 0,1
    ) 
);

#  Mode 4 :
FROM employees e, (
	SELECT department_id, MAX(salary) max_sal
    FROM employees
    GROUP BY department_id
    ORDER BY max_sal ASC
    LIMIT 0,1
) t_dept_max_sal
WHERE e.`department_id` = t_dept_max_sal.`department_id`;
  1. Check the Department with the highest average wage manager Details of :last_name, department_id, email, salary
SELECT last_name, department_id, email, salary
FROM employees
WHERE employee_id IN (
	SELECT DISTINCT manager_id
    FROM employees
    WHERE department_id = (
    	SELECT department_id
        FROM employees
        GROUP BY department_id
        HAVING AVG(salary) = (
        	SELECT MAX(avg_sal)
            FROM (
            	SELECT AVG(salary) avg_sal
                FROM employees
                GROUP BY department_id
            ) t_dept_avg_sal
        )
    )
);

SELECT last_name, department_id, email, salary
FROM employees
WHERE employee_id IN (
    SELECT DISTINCT manager_id
    FROM employees e, (
        SELECT department_id, AVG(salary) avg_sal
        FROM employees
        GROUP BY department_id
        ORDER BY avg_sal DESC
        LIMIT 0,1
    ) t_dept_avg_sal
    WHERE e.`department_id` = t_dept_avg_sal.`department_id`
);
  1. Query the department number of the Department , It does not include job_id yes "ST_CLERK" Your department number
SELECT department_id
FROM departments
WHERE department_id NOT IN (
	SELECT DISTINCT department_id
    FROM employees
    WHERE job_id = `ST_CLERK`
);

SELECT department_id
FROM department d
WHERE NOT EXISTS (
	SELECT *
    FROM employees e
    WHERE d.`department_id` = e.`department_id`
    AND e.`job_id` = 'ST_CLERK'
);
  1. Select all employees without managers last_name
SELECT last_name
FROM employees emp
WHERE NOT EXISTS (
	SELECT *
    FROM employees mgr
    WHERE emp.`manager_id` = mgr.`employee_id`
);
  1. Check the employee number 、 full name 、 Employment time 、 Wages , The manager of the employee is ‘De Haan’
SELECT employee_id, last_name, hire_date, salary
FROM employee
WHERE manager_id IN (
	SELECT manager_id
    FROM employee
    WHERE last_name = 'De Haan'
);
  1. Query the employee number of employees in each department whose salary is higher than the average salary of the Department , Name and salary ( Correlation subquery )
SELECT department_id, last_name, salary
FROM employees e1
WHERE salary > (
	SELECT AVG(salary)
    FROM employees e2
    WHERE e2.`department_id` = e1.`department_id`
);

SELECT e.last_name, e.salary, e.department_id
FROM employees e, (
	SELECT department_id, AVG(salary) avg_sal
    FROM employees
    GROUP BY department_id
) t_dept_avg_sal
WHERE e.`department_id` = t_dept_avg_sal.`department_id`
AND e.`salary` > t_dept_avg_sal.`avg_sal`;
  1. Query the number of departments under each department is greater than 5 Department name of ( Correlation subquery )
SELECT department_name
FROM departments d
WHERE 5 < (
	SELECT COUNT(*)
    FROM employees e
    WHERE d.`department_id` = e.`department_id`
);
  1. The number of departments in each country is greater than 2 Country number of ( Correlation subquery )
SELECT country_id
FROM locations l
WHERE 2 < (
	SELECT COUNT(*)
    FROM department d
    WHERE l.`location_id` = d.`location_id`
);

Chapter ten _ Create and manage tables

1. Basic knowledge of

1) Identifier naming rules

  • Database name 、 The table name must not exceed 30 Characters , Variable names are limited to 29 individual
  • Must contain only A–Z, a–z, 0–9, _ common 63 Characters
  • Database name 、 Table name 、 Do not include spaces in object names such as field names
  • The same MySQL In software , The database cannot have the same name ; In the same library , A watch cannot have the same name ; In the same table , The field cannot have the same name
  • You must ensure that your field has no and reserved words 、 Database systems or common methods conflict . If you insist on using , Please be there. SQL In a sentence, make use `( mark of emphasis ) Lead up
  • Keep field names and types consistent : When naming fields and specifying data types for them, be sure to ensure consistency , If data Type is an integer in a table , Then don't turn into character in another table

2) MySQL Data types in

type Data variable
Integer types TINYINT、SMALLINT、MEDIUMINT、INT( or INTEGER)、BIGINT
Floating point type FLOAT、DOUBLE
Fixed point number type DECIMAL
A type of BIT
Date time type YEAR、TIME、DATE、DATETIME、TIMESTAMP
Text string type CHAR、VARCHAR、TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT
Enumeration type ENUM
Collection types SET
Binary string type BINARY、VARBINARY、TINYBLOB、BLOB、MEDIUMBLOB、LONGBLOB
JSON type JSON object 、JSON Array
Spatial data types Single value :GEOMETRY、POINT、LINESTRING、POLYGON; aggregate :MULTIPOINT、MULTILINESTRING、MULTIPOLYGON、 GEOMETRYCOLLECTION

among , Several common types are introduced as follows :

data type describe
INT from -231 To 231-1 The integer data of . The storage size is 4 Bytes
CHAR(size)FLOAT、DOUBLE
VARCHAR(size)DECIMAL
FLOAT(M,D)BIT
DOUBLE(M,D)YEAR、TIME、DATE、DATETIME、TIMESTAMP
DECIMAL(M,D)CHAR、VARCHAR、TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT
DATEENUM
BLOBSET
TEXTBINARY、VARBINARY、TINYBLOB、BLOB、MEDIUMBLOB、LONGBLOB

2. Create and manage databases

1) Create database

  • The way 1: Create database

    CREATE DATABASE  Database name ;
    
  • The way 2: Create database and specify character set

    CREATE DATABASE  Database name  CHARACTER SET  Character set ;
    
  • The way 3: Determine whether the database already exists , If it does not exist, create the database ( recommend )

    CREATE DATABASE IF NOT EXISTS  Database name ;
    

If MySQL The relevant database already exists , The create statement is ignored , No more database creation .

Be careful :DATABASE You can't change your name . Some visualization tools can be renamed , It's building a new library , Copy all tables to the new library , Delete again Old Library completed .

2) Using a database

  • View all current databases

    SHOW DATABASES; # There is one S, Representing multiple databases 
    
  • View the database currently in use

    SELECT DATABASE(); # One used  mysql  Global functions in 
    
  • View all tables under the specified library

    SHOW TABLES FROM  Database name 
    
  • View database creation information

    SHOW CREATE DATABASE  Database name ;
     perhaps :
    SHOW CREATE DATABASE  Database name \G
    
  • Use / Switch database

    USE  Database name ;
    

Be careful : Before operating tables and data, you must first explain which database you are operating on , Otherwise, add... To all objects “ Count According to the library name .”.

3) modify the database

  • Change the database character set

    ALTER DATABASE  Database name  CHARACTER SET  Character set ; # such as :gbk、utf8 etc. 
    
  • The way 1: Delete the specified database

    DROP DATABASE  Database name ;
    
  • The way 2: Delete the specified database ( recommend )

    DROP DATABASE IF EXISTS  Database name ;
    

3. Create table

1) How it was created 1

  • Grammar format :
CREATE TABLE [IF NOT EXISTS]  Table name (
 Field 1,  data type  [ constraint condition ] [ The default value is ],
 Field 2,  data type  [ constraint condition ] [ The default value is ],
 Field 3,  data type  [ constraint condition ] [ The default value is ],
……
[ Table constraints ]
);

Combined with the IF NOT EXISTS keyword , said : If the data table to be created does not exist in the current database , Then create a data table ; If the data table to be created already exists in the current database , The table creation statement is ignored , No longer create data table .

2) How it was created 2

  • Use AS subquery Options , Combine creating tables with inserting data
CREATE TABLE  Table name 
	[(column, column, ...)]
AS subquery;
  • The specified column should correspond to the column in the subquery one by one
  • Define columns by column names and default values
CREATE TABLE dept80
AS
SELECT employee_id, last_name, salary*12 ANNSAL, hire_date
FROM employees
WHERE department_id = 80;

3) Look at the data table structure

stay MySQL After creating the data table in , You can view the structure of the data table .MySQL Support use DESCRIBE/DESC Statement to view data Table structure , Also supports the use of SHOW CREATE TABLE Statement to view the data table structure .

The syntax is as follows :

SHOW CREATE TABLE  Table name \G

Use SHOW CREATE TABLE Statement can not only view the detailed statement when the table is created , You can also view the storage engine and character encoding .

4. Modify table

Modifying a table means modifying the structure of a data table that already exists in the database .

Use ALTER TABLE Statement can realize :

  • Add columns to existing tables
  • Modify columns in existing tables
  • Delete columns from existing tables
  • Rename columns in an existing table

1) Append a column

The syntax is as follows :

ALTER TABLE  Table name  ADD 【COLUMN】  Field name   Field type  【FIRST|AFTER  Field name 】;

give an example :

ALTER TABLE dept80
ADD job_id varchar(15);

2) Modify a column

  • You can modify the data type of the column , length 、 Default values and locations
  • Modify field data type 、 length 、 The default value is 、 The syntax format of the location is as follows :
ALTER TABLE  Table name  MODIFY 【COLUMN】  Field name 1  Field type  【DEFAULT  The default value is 】【FIRST|AFTER  Field name 2】;
  • give an example :
ALTER TABLE dept80
MODIFY salary double(9,2) default 1000;
  • Changes to the default value only affect future changes to the table
  • Besides , You can also modify column constraints in this way .

3) Rename a column

Use CHANGE old_column new_column dataType Clause renames the column . The syntax is as follows :

ALTER TABLE  Table name  CHANGE 【column】  Name   New column names   New data types ;

give an example :

ALTER TABLE dept80
CHANGE department_name dept_name varchar(15);

4) Delete a column

The syntax format of deleting a field in the table is as follows :

ALTER TABLE  Table name  DROP 【COLUMN】 Field name 

5) Change table name

  • Mode one : Use RENAME
RENAME TABLE emp
TO myemp;
  • Mode two :
ALTER table dept
RENAME [TO] detail_dept; -- [TO] It can be omitted 
  • Must be the owner of the object

5. Delete table

  • stay MySQL in , When a data sheet No association with any other data table when , You can delete the current data table directly .
  • Data and structures are deleted
  • All running related transactions are committed
  • All relevant indexes are deleted
  • Grammar format :
DROP TABLE [IF EXISTS]  Data sheet 1 [,  Data sheet 2, …,  Data sheet n];

IF EXISTS Means : If the corresponding data table exists in the current database , Delete the data table ; If there is no... In the current database In the corresponding data sheet , Delete statement is ignored , No longer delete the data table .

give an example :

DROP TABLE dept80;
  • DROP TABLE Statement cannot be rolled back

6. Clear the table

  • TRUNCATE TABLE sentence :
    • Delete all data in the table
    • Free the storage space of the table
  • give an example :
TRUNCATE TABLE detail_dept;
  • TRUNCATE Statement cannot be rolled back , While using DELETE Statement delete data , You can roll back

Ali Development Specification : 【 Reference resources 】TRUNCATE TABLE Than DELETE Fast , It also uses less system and transaction log resources , but TRUNCATE nothing Transaction without triggering TRIGGER, Possible accidents , It is not recommended to use this statement in development code . explain :TRUNCATE TABLE In function and without WHERE Clause DELETE Same statement .

7. Content expansion

expand 1: Alibaba 《Java Development Manual 》 And MySQL Field naming

  • 【 mandatory 】 Table name 、 Field names must be lowercase letters or numbers , No beginning of number , Forbid two underscores to appear only in the middle Now the number . The modification of database field names costs a lot , Because pre release is not possible , So field names need to be carefully considered .

    • Example :aliyun_admin,rdc_config,level3_name
    • Counter example :AliyunAdmin,rdcConfig,level_3_name
  • 【 mandatory 】 Disable reserved words , Such as desc、range、match、delayed etc. , Please refer to MySQL Official reserved word .

  • 【 mandatory 】 Table required three fields :id, gmt_create, gmt_modified.

    • explain : among id Primary key required , The type is BIGINT UNSIGNED、 Self increasing in single table 、 In steps of 1.gmt_create, gmt_modified The types of are DATETIME type , The former now stands for active creation , The latter past participle means being Dynamic update
  • 【 recommend 】 The best way to name a table is to follow “ Business name _ Function of table ”.

    • Example :alipay_task 、 force_project、 trade_config
  • 【 recommend 】 The library name and application name should be consistent as much as possible .

  • 【 Reference resources 】 Appropriate character storage length , Not only save database table space 、 Save index storage , More importantly, improve the retrieval speed .

    • Example : Unsigned values can avoid false negative numbers , And expand the scope of representation .

Expand 2: Operation precautions:

  • Table delete The operation will delete the definition of the table and the data in the table , also MySQL When deleting , There will be no confirmation letter Information tips , Therefore, you should be careful when deleting . Before deleting the table , It is best to compare the data in the table Backup , In this way, when the operation is wrong, you can To recover data , So as not to cause irreparable consequences .
  • alike , In the use of ALTER TABLE During the basic modification operation of the table , Before performing the operation process , It should also be ensured that the data is Line complete Backup , Because the database changes are Can't undo Of , If you add an unnecessary field , It can be deleted ; phase Identical , If you delete a required column , All data below this column will be lost .

Expand 3:MySQL8 New characteristics —DDL Atomization of

stay MySQL 8.0 In the version ,InnoDB Tabular DDL Support transaction integrity , namely DDL The operation either succeeds or rolls back .DDL Operation rollback log Write to data dictionary Data dictionary table mysql.innodb_ddl_log( The table is a hidden table , adopt show tables Can't see ) in , For rollback operations . By setting parameters , Can be DDL Print and output operation log to MySQL In the error log .

The first 11 Chapter _ Addition, deletion and modification of data processing

1. insert data

1) The way 1:VALUES The way to add

Using this syntax, only one piece of data can be inserted into the table at a time .

situation 1: Inserts data in the default order for all fields of the table

INSERT INTO  Table name 
VALUES (value1,value2,....);

In the value list, you need to specify a value for each field of the table , And the order of values must be the same as that of fields in the data table .

give an example :

INSERT INTO departments
VALUES (70, 'Pub', 100, 1700);

situation 2: Specify the field name to insert data

Insert data for the specified fields of the table , Is in the INSERT Statement inserts values into only some fields , The values of other fields are the values of the table definition The default value is . stay INSERT Column names are arbitrarily listed in the clause , But once listed ,VALUES To insert value1,…valuen Need and column1,…columnn The columns correspond one by one . If the type is different , Will not be able to insert , also MySQL There will be mistakes .

give an example :

INSERT INTO departments(department_id, department_name)
VALUES (80, 'IT');

situation 3: Insert multiple records at the same time

INSERT Statement can insert multiple records into the data table at the same time , Specify multiple value lists when inserting , Each value list is separated by commas open , The basic syntax is as follows :

INSERT INTO table_name
VALUES
(value1 [,value2, …, valuen]),
(value1 [,value2, …, valuen]),
……
(value1 [,value2, …, valuen]);

perhaps

INSERT INTO table_name(column1 [, column2, …, columnn])
VALUES
(value1 [,value2, …, valuen]),
(value1 [,value2, …, valuen]),
……
(value1 [,value2, …, valuen]);

Use INSERT When inserting multiple records at the same time ,MySQL It will return some additional information that is not available when performing single line insertion , The content of this information The meaning is as follows :

  • Records: Indicates the number of records inserted .
  • Duplicates: Indicates the records that were ignored during insertion , The reason may be that Some records contain duplicate primary key values .
  • Warnings: Data values indicating a problem , For example, data type conversion occurs .

A that inserts multiple rows of records at the same time INSERT Statement is equivalent to multiple single line inserts INSERT sentence , But multi line INSERT sentence During processing More efficient . because MySQL Execute a single article INSERT Statement inserts more rows of data than using multiple INSERT sentence fast , Therefore, when inserting multiple records, it is best to choose to use a single record INSERT Insert... In the form of a statement .

2) The way 2: Insert the query results into the table

INSERT Can also be SELECT Insert the result of the statement query into the table , At this time, it is not necessary to input the values of each record one by one , Just use one INSERT Statement and a line SELECT Statements can quickly insert multiple rows from one or more tables into a table

INSET INTO  Target table name 
(tar_column1 [, tar_column2, ..., tar_columnn])
SELECT
(src_column1 [, src_column2, …, src_columnn])
FROM  Source table name 
[WHERE condition]
  • stay INSERT Add a subquery to the statement .
  • There's no need to write VALUES Clause .
  • The list of values in the subquery should be the same as INSERT The column name in Clause corresponds to .
INSERT INTO emp2
SELECT *
FROM employees
WHERE department_id = 90;
INSERT INTO sales_reps(id, name, salary, commission_pct)
SELECT employee_id, last_name, salary, commission_pct
FROM employees
WHERE job_id LIKE '%REP%';

2. Update data

  • Use UPDATE Statement update data . The grammar is as follows :
UPDATE table_name
SET column1=value1, column2=value2, ..., column=valuen
[WHERE condition]
  • You can update more than one piece of data at a time .

  • If you need to roll back data , It needs to be guaranteed in DML front , Set it up :SET AUTOCOMMIT = FALSE;

  • Use WHERE Clause specifies the data to be updated .

UPDATE employees
SET department_id = 70
WHERE employee_id = 113;
  • If omitted WHERE Clause , Then all data in the table will be updated .

3. Delete data

DELETE FROM table_name [WHERE <condition>];

table_name Specify the table to delete ;“[WHERE ]” Is an optional parameter , Specify deletion criteria , without WHERE Clause , DELETE Statement will delete all records in the table .

4. MySQL8 New characteristics : Calculated column

What is a calculated column ? Simply put, the value of a column is calculated from other columns . for example ,a The column value is 1、b The column value is 2,c Column Manual insertion is not required , Definition a+b As the result of the c Value , that c Is the calculation column , It is calculated from other columns .

stay MySQL 8.0 in ,CREATE TABLE and ALTER TABLE Both support adding calculation Columns . Let's say CREATE TABLE For example .

give an example : Define data table tb1, Then define the fields id、 Field a、 Field b And field c, Which field c Is a calculated column , Used to calculate a+b Of value . First create a test table tb1, The statement is as follows :

CREATE TABLE tb1(
id INT,
a INT,
b INT,
c INT GENERATED ALWAYS AS (a + b) VIRTUAL
);

The first 12 Chapter _MySQL Data type refinement

1. MySQL Data types in

type give an example
Integer types TINYINT、SMALLINT、MEDIUMINT、INT( or INTEGER)、BIGINT
Floating point type FLOAT、DOUBLE
Fixed point number type DECIMAL
A type of BIT
Date time type YEAR、TIME、DATE、DATETIME、TIMESTAMP
Text string type CHAR、VARCHAR、TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT
Enumeration type ENUM
Collection types SET
Binary string type BINARY、VARBINARY、TINYBLOB、BLOB、MEDIUMBLOB、LONGBLOB
JSON type JSON object 、JSON Array
Spatial data types Single value type :GEOMETRY、POINT、LINESTRING、POLYGON; Collection types :MULTIPOINT、MULTILINESTRING、MULTIPOLYGON、 GEOMETRYCOLLECTION

Properties of common data types , as follows :

MySQL keyword meaning
NULLTINYINT、SMALLINT、MEDIUMINT、INT( or INTEGER)、BIGINT
NOT NULLFLOAT、DOUBLE
DEFAULTDECIMAL
PRIMARY KEYBIT
AUTO_INCREMENTYEAR、TIME、DATE、DATETIME、TIMESTAMP
UNSIGNEDCHAR、VARCHAR、TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT
CHARACTER SET nameENUM

2. Integer types

1) Type introduction

Integer types have a total of 5 Kind of , Include TINYINT、SMALLINT、MEDIUMINT、INT(INTEGER) and BIGINT.

The differences between them are shown in the table below :

Integer types byte The value range of signed number The value range of the unsigned number
TINYINT1-128~1270~255
SMALLINT2-32768~327670~65535
MEDIUMINT3-8388608~83886070~16777215
INT、INTEGER4-2147483648~21474836470~4294967295
BIGINT8-9223372036854775808~92233720368547758070~18446744073709551615

2) Optional attribute

There are three optional properties of integer type :

  • M

M : Indicates the display width ,M The range of phi is zero (0, 255). for example ,int(5): When the data width is less than 5 You need to use... In front of the number when you are in bits Character fill width . This function needs to cooperate with “ ZEROFILL ” Use , To express with “0” Fill the width , Otherwise, the specified display width is invalid . If the display width is set , Then the inserted data width exceeds the display width limit , Will truncation or insertion fail ?

answer : There will be no impact on the inserted data , Or is it saved according to the actual width of the type , namely Displays the width and type of information that can be stored Value range independent . from MySQL 8.0.17 Start , The display width property is not recommended for integer data types . The integer data type can specify the required display width when defining the table structure , If you don't specify , The system specifies the default value for each type The width value of .

give an example :

CREATE TABLE test_int1 ( x TINYINT, y SMALLINT, z MEDIUMINT, m INT, n BIGINT );

View table structure (MySQL5.7 The explicit expression is as follows ,MySQL8 The scope is no longer explicit in )

mysql> desc test_int1;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| x | tinyint(4) | YES | | NULL | |
| y | smallint(6) | YES | | NULL | |
| z | mediumint(9) | YES | | NULL | |
| m | int(11) | YES | | NULL | |
| n | bigint(20) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

TINYINT The value ranges of signed and unsigned numbers are -128~127 and 0~255, Because the minus sign occupies a digit , therefore TINYINT The default display width is 4. Empathy , The default display width of other integer types is the same as the minimum value of the signed number .

  • UNSIGNED

UNSIGNED : Unsigned type ( non-negative ), All integer types have an optional property UNSIGNED( Unsigned attribute ), nothing The minimum value of signed integer type is 0. therefore , If you need to MySQL When saving non negative integer values in the database , You can set the integer type to Set to unsigned type . int The default display width of the type is int(11), Unsigned int The default display width of the type is int(10).

  • ZEROFILL

ZEROFILL : 0 fill ,( If a column is ZEROFILL, that MySQL Will automatically add... For the current column UNSIGNED attribute ), If it means Set the ZEROFILL It just means it's not enough M When a , use 0 Fill in on the left , If exceeded M position , As long as it does not exceed the data storage range .

original , stay int(M) in ,M It's worth it int(M) It doesn't matter how much storage space it takes . int(3)、int(4)、int(8) It's all on disk It's occupation 4 bytes Storage space . in other words ,int(M), It has to be with UNSIGNED ZEROFILL It makes sense to use them together . If the whole Value exceeds M position , It is stored according to the actual number of bits . Just no more characters 0 Fill in .

3) Applicable scenario

TINYINT : Generally used to enumerate data , For example, the system sets a small and fixed value range .

SMALLINT : It can be used for a small range of Statistics , For example, count the fixed asset inventory of the factory .

MEDIUMINT : Used for the calculation of larger integers , For example, the daily passenger flow of the station .

INT、INTEGER : The value range is large enough , In general, the problem of overrun does not need to be considered , Most used . Such as item number .

BIGINT : Only when you deal with very large integers will you use . For example, the trading volume of double 11 、 Large portal hits 、 Prove Securities companies, derivatives positions, etc .

4) How to choose ?

When evaluating which integer type to use , You need to think about Storage space and reliability The balance of : a party Noodles , Use less bytes Can save storage space ; On the other hand , In order to save storage space , The value range of integer type used is too small , One In case of exceeding the value range , It could cause System error , Affect reliability .

for instance , The data type used for the item number is INT. And the reason is that , There are many kinds of goods circulating in customer stores , and , Every time Every day there are old goods off the shelves , New products on the shelves , So keep iterating , Accumulate over a long period .

If you use SMALLINT type , Although it takes up more bytes than INT There are fewer integers of type , But there is no guarantee that the data will not go out of range 65535. contrary , Use INT, You can ensure that there is a large enough value range , Don't worry about data out of range affecting reliability .

What you should pay attention to is , In practice , The cost of system failure far exceeds the cost of adding storage space for several fields . because this , I suggest you first make sure that the data does not exceed the value range , Under this premise , Then consider how to save storage space .

3. Floating point type

1) Type introduction

Floating point number and fixed-point number types are characterized by Deal with decimals , You can think of integers as a special case of decimals . therefore , Floating point numbers and fixed points Number of usage scenarios , Much larger than integers . MySQL Supported floating point number types , Namely FLOAT、DOUBLE、REAL.

  • FLOAT Represents a single precision floating-point number ;

  • DOUBLE Represents a double precision floating-point number ;

  • REAL The default is DOUBLE. If you put SQL The mode is set to enable “ REAL_AS_FLOAT ”, that Well ,MySQL I think REAL yes FLOAT. If you want to enable “REAL_AS_FLOAT”, You can use the following SQL Statements for :

    SET sql_mode = “REAL_AS_FLOAT”;
    

problem : Why is the value range of unsigned number of floating-point number type , It is only half of the value range of signed numbers , That is, it is only equivalent to The part of the signed number whose value range is greater than or equal to zero ?

MySQL The format for storing floating-point numbers is : Symbol (S) 、 mantissa (M) and Order code (E) . therefore , With or without symbols ,MySQL Floating The number of symbols will be stored . therefore , The so-called unsigned number value range , In fact, the value range of signed number is greater than or equal to The zero part .

2) Data accuracy description

For floating point types , stay MySQL Single precision values in use 4 Bytes , Double values use 8 Bytes .

  • MySQL Allow to use Nonstandard grammar ( Other databases may not support , So if it comes to data migration , It's best not to use ): FLOAT(M,D) or DOUBLE(M,D) . here ,M be called precision ,D be called scale .(M,D) in M= Integer bit + decimal position ,D= Decimal places . D<=M<=255,0<=D<=30.

    for example , Defined as FLOAT(5,2) A column of can be displayed as -999.99-999.99. If you exceed this range, you will report an error .

  • FLOAT and DOUBLE Type is not specified (M,D) when , By default, it will follow the actual precision ( It depends on the actual hardware and operating system ) To display .

  • explain : Floating point type , You can also add UNSIGNED , However, the data range will not be changed , for example :FLOAT(3,2) UNSIGNED still It can only mean 0-9.99 The scope of the .

  • Whether or not the precision is explicitly set (M,D), here MySQL The treatment plan is as follows :

    • If in storage , The integer part is out of range ,MySQL You're going to report a mistake , It is not allowed to store such value
    • If in storage , If the decimal part is out of range , In the following cases :
      • If after rounding , The integer part is not out of range , Just a warning , However, it can be successfully operated and rounded to delete redundant Save after decimal places . For example, in FLOAT(5,2) Insert... In the column 999.009, The approximate result is 999.01.
      • If after rounding , The integer part is out of range , be MySQL Report errors , And refuse to deal with . Such as FLOAT(5,2) Insert... In the column 999.995 and -999.995 All will report wrong. .
  • from MySQL 8.0.17 Start ,FLOAT(M,D) and DOUBLE(M,D) Usage is clearly not recommended in the official documents , In the future Can be removed . in addition , About floating point FLOAT and DOUBLE Of UNSIGNED It is not recommended to use , It may also be removed in the future .

3) Accuracy error description

Floating point type has a flaw , It's just not accurate . Let me explain why MySQL The floating point number is not accurate enough . such as , I We design a watch , Yes f1 This field , The insertion values are 0.47,0.44,0.19, The result we expect is :0.47 + 0.44 + 0.19 = 1.1. While using sum Query after :

CREATE TABLE test_double2(
f1 DOUBLE
);
INSERT INTO test_double2
VALUES(0.47),(0.44),(0.19);
mysql> SELECT SUM(f1)
-> FROM test_double2;
+--------------------+
| SUM(f1) |
+--------------------+
| 1.0999999999999999 |
+--------------------+
1 row in set (0.00 sec)

The result is 1.0999999999999999. Did you see? ? Although the error is small , But there are errors . You can also try to put data types Change to FLOAT, Then run the summation query , Get is , 1.0999999940395355. obviously , The error is even greater .

that , Why is there such an error ? The problem is MySQL The storage method of floating-point data .

MySQL use 4 Byte store FLOAT Type data , use 8 Bytes to store DOUBLE Type data . No matter which , They all use two Hexadecimal way to store . such as 9.625, Express in binary , Namely 1001.101, Or expressed as 1.001101×2^3. Such as The fruit mantissa is not 0 or 5( such as 9.624), You can't use a binary number to express . , in turn, , So we have to choose the allowable range Round off .

In programming , If floating-point numbers are used , Pay special attention to the error , Because floating point numbers are inaccurate , So we should avoid using “=” Come on To determine if two Numbers are equal . meanwhile , In some projects that require high accuracy , Never use floating point numbers , Otherwise, it will lead to knot If something goes wrong , Even cause irreparable losses . that ,MySQL Is there a precise data type ? Of course. , This is the fixed-point number type : DECIMAL .

4. Fixed point number type

1) Type introduction

  • MySQL The fixed-point number type in is only DECIMAL One type .
type byte The value range of signed number
DECIMAL(M,D),DEC,NUMERICM+2 byte The valid range consists of M and D decision

Use DECIMAL(M,D) High precision decimals are represented in the form of . among ,M It is called precision ,D It's called scaling .0<=M<=65, 0<=D<=30,D

  • DECIMAL(M,D) The maximum value range of is the same as DOUBLE Same type , But the valid data range is determined by M and D Decisive . DECIMAL The storage space is not fixed , By the precision value M decision , The total storage space occupied is M+2 Bytes . That is to say say , In some scenes with low accuracy requirements , Compared with the fixed-point number occupying the same byte length , The range of values represented by floating-point numbers can be In a larger way .
  • The fixed point number is in MySQL The interior is made up of character string Storage in the form of , This determines that it must be accurate .
  • When DECIMAL When the type does not specify precision and scale , His tacit view is that DECIMAL(10,0). When the precision of the data exceeds that of the fixed-point number type Accuracy range , be MySQL Rounding is also performed .
  • Floating point numbers vs Fixed-point number
    • The advantage of floating-point numbers over fixed-point numbers is that when the length is fixed , Floating point type has a wide range of values , But it's not accurate , apply It needs a wide range of values , It can also tolerate small errors in scientific computing scenarios ( Like computational chemistry 、 Molecular modeling 、 Hydrodynamic Mechanics, etc )
    • The value range of fixed-point number type is relatively small , But accuracy , There is no error , It is suitable for scenes with high precision requirements ( For example, involving And the scenario of amount calculation )

2) Experience in development

“ because DECIMAL Accuracy of data types , In our project , Except for a few ( Such as item number ) Use integer type Outside , The other values are DECIMAL, The reason is that the retail industry of this project , Accuracy is required , Not a penny Bad . ” —— From a project manager

5. A type of :BIT

BIT Type stores binary values , similar 010110.

Binary string type length Length range Occupancy space
BIT(M)M1 <= M <= 64 about (M + 7)/8 Bytes

BIT type , If not specified (M), The default is 1 position . This 1 position , Indicates that only 1 Binary value of bit . here (M) It represents binary digit , The minimum number of digits is 1, The maximum value is 64.

6. Date and time type

Date and time are important information , In our system , Almost all data sheets can be used . The reason is that customers need to know the data Time tags , So as to query the data 、 Statistics and processing .

MySQL There are many data types that represent dates and times , Different versions may be different ,MySQL8.0 Date and time supported by version The main types are :YEAR type 、TIME type 、DATE type 、DATETIME The type and TIMESTAMP type .

  • YEAR Type is usually used to represent year
  • DATE Type is usually used to represent year 、 month 、 Japan
  • TIME Types are often used to indicate when 、 branch 、 second
  • DATETIME Type is usually used to represent year 、 month 、 Japan 、 when 、 branch 、 second
  • TIMESTAMP Type is usually used to represent a year with a time zone 、 month 、 Japan 、 when 、 branch 、 second
type name byte Date format minimum value Maximum
YEAR year 1YYYY or YY19012155
TIME Time 3HH:MM:SS-838:59:59838:59:59
DATE date 3YYYY-MM-DD1000-01-019999-12-03
DATETIME Date time 8YYYY-MM-DD HH:MM:SS1000-01-01 00:00:009999-12-31 23:59:59
TIMESTAMP Date time 4YYYY-MM-DD HH:MM:SS1970-01-01 00:00:00 UTC2038-01-19 03:14:07UTC

You can see , Different data types represent different time contents 、 The value range is different , And the number of bytes occupied is also different , You have to rely on Flexible selection is required in practice .

Why time type TIME The value range of is not -23:59:59~23:59:59 Well ? as a result of MySQL The design of the TIME type , Not only watch Show the time of day , And it can be used to represent a time interval , This interval can exceed 24 Hours .

7. Text string type

MySQL in , Text strings are generally divided into CHAR 、 VARCHAR 、 TINYTEXT 、 TEXT 、 MEDIUMTEXT 、 LONGTEXT 、 ENUM 、 SET Other types .

8. ENUM type

ENUM Types are also called enumeration types ,ENUM The value range of type needs to be specified when defining the field . When setting field values ,ENUM Type allows only a single value to be selected from a member , You cannot select more than one value at a time . The required storage space is defined by ENUM Type is determined by the number of members specified .

Text string type length Length range Occupied storage space
ENUML1 <= L <= 655351 or 2 Bytes
  • When ENUM The type contains 1~255 When a member , need 1 Bytes of storage space ;
  • When ENUM The type contains 256~65535 When a member , need 2 Bytes of storage space .
  • ENUM The maximum number of members of type is 65535 individual .

9. SET type

When SET Type contains different number of members , The storage space it occupies is also different , As follows :

Number range of members (L Indicates the actual number of members ) Occupied storage space
1 <= L <= 81 Bytes
9 <= L <= 162 Bytes
17 <= L <= 243 Bytes
25 <= L <= 324 Bytes
33 <= L <= 648 Bytes

SET The more members a type has when storing data , The larger the storage space it takes . Be careful :SET Type when selecting members , One time Select multiple members , This is related to ENUM Different types .

13. Summary and selection suggestions

When defining data types , If it is Integers , Just use INT ; If it is decimal , Be sure to use the fixed-point number type DECIMAL(M,D) ; If it's a date and time , Just use DATETIME . The advantage of this is , First, make sure your system doesn't make mistakes because of data type definition . however , Everything has two sides , reliability good , It doesn't mean efficient . such as ,TEXT Although easy to use , But not as efficient as CHAR(M) and VARCHAR(M).

Alibaba 《Java Development Manual 》 And MySQL database :

  • If any field is non negative , Must be UNSIGNED

  • 【 mandatory 】 Decimal type is DECIMAL, No use FLOAT and DOUBLE.

    explain : At the time of storage ,FLOAT and DOUBLE There is a problem of precision loss , Most likely when comparing values , Get the wrong result . If the range of data stored exceeds DECIMAL The scope of the , It is recommended to divide the data into integers and decimals and store them separately .

  • 【 mandatory 】 If the stored string length is almost equal , Use CHAR Fixed length string type .

  • 【 mandatory 】VARCHAR Is a variable length string , Do not pre allocate storage space , Do not exceed the length 5000. If the storage length is greater than this value , Define field type as TEXT, Come up with a table , Match with primary key , Avoid affecting the index efficiency of other fields .

The first 13 Chapter _ constraint

1. Classification of constraints

  • According to the restrictions of constraint data columns , Constraints can be divided into :
    • Single column constraints : Each constraint constrains only one column
    • Multi column constraint : Each constraint can constrain multiple columns of data
  • According to the scope of the constraint , Constraints can be divided into :
    • Column level constraints : Can only act on one column , Follow the definition of the column
    • Table level constraints : Can act on multiple columns , Not with columns , It is defined separately
  • According to the role of constraints , Constraints can be divided into :
    • NOT NULL Non empty constraint , Specifies that a field cannot be empty
    • UNIQUE Unique constraint , Specify that a field is unique in the whole table
    • PRIMARY KEY Primary key ( Non empty and unique ) constraint
    • FOREIGN KEY Foreign key constraints
    • CHECK Check constraint
    • DEFAULT Default constraint

Be careful : MySQL I won't support it check constraint , But you can use check constraint , Without any effect

  • How to add / Delete constraints ?

CREATE TABLE Add constraints when

ALTER TABLE Add constraints when 、 Delete constraints

  • View the existing constraints of a table
#information_schema Database name ( System libraries )
#table_constraints The name of the table ( Store constraints for individual tables )
SELECT * FROM information_schema.table_constraints
WHERE table_name = ' The name of the table ';

2. Non empty constraint

1) effect

Limit a field / The value of a column cannot be empty

2) keyword

NOT NULL

3) characteristic

  • Default , All types of values can be NULL, Include INT、FLOAT And so on
  • Non empty constraints can only appear on columns of table objects , Only one column can be qualified as non empty , Cannot combine non empty
  • A table can have many columns, which are limited to non empty
  • An empty string ’' It's not equal to NULL,0 Also is not equal to NULL

4) Add non empty constraints

1. Build table

CREATE TABLE  The name of the table (
 Field name   data type ,
 Field name   data type  NOT NULL,
 Field name   data type  NOT NULL
);

2. After the establishment of the table

alter table  The name of the table  modify  Field name   data type  not null;

5) Delete non empty constraints

alter table  The name of the table  modify  Field name   data type  NULL;# Get rid of not null, It is equivalent to modifying a non annotation field , This field can be empty 
 or 
alter table  The name of the table  modify  Field name   data type ;# Get rid of not null, It is equivalent to modifying a non annotation field , This field can be empty 

3. Uniqueness constraint

1) effect

Used to restrict a field / The value of a column cannot be repeated .

2) keyword

UNIQUE

3) characteristic

  • The same table can have multiple unique constraints .
  • A unique constraint can be a unique value for a column , You can also combine multiple columns to have unique values .
  • The uniqueness constraint allows column values to be empty .
  • When creating unique constraints , If you don't name a unique constraint , The default is the same as the column name .
  • MySQL A unique index will be created by default for columns with unique constraints .

4) Add unique constraints

1. Build table

create table  The name of the table (
 Field name   data type ,
 Field name   data type  unique,
 Field name   data type  unique key,
 Field name   data type 
);

create table  The name of the table (
 Field name   data type ,
 Field name   data type ,
 Field name   data type ,
[constraint  Constraint name ] unique key( Field name )
);

give an example :

CREATE TABLE USER(
id INT NOT NULL,
NAME VARCHAR(25),
PASSWORD VARCHAR(16),
--  Use table level constraint syntax 
CONSTRAINT uk_name_pwd UNIQUE(NAME,PASSWORD)
);

Indicates that the combination of user name and password cannot be repeated

2. Specify the only key constraint after creating the table

# If it is a field in the field list , Indicates that the value of this column is unique . If there are two or more fields , So the compound is unique , That is, the combination of multiple fields is unique 
 One 
# The way 1:
alter table  The name of the table  add unique key( Field list );
# The way 2:
alter table  The name of the table  modify  Field name   Field type  unique;

5) About compound unique constraints

create table  The name of the table (
 Field name   data type ,
 Field name   data type ,
 Field name   data type ,
unique key( Field list ) # Multiple field names are written in the field list , Multiple field names are separated by commas , It means that it is compound and unique , That is more 
 The combination of two fields is unique 
);

6) Delete unique constraint

  • A unique index will also be automatically created on the column to which the uniqueness constraint is added .
  • Deleting a unique constraint can only be deleted by deleting a unique index .
  • You need to specify a unique index name when deleting , The unique index name is the same as the unique constraint name .
  • If you do not specify a name when creating a unique constraint , If it's a single column , The default is the same as the column name ;
  • If it's a composite column , Then default and () The first column in the list has the same name . You can also customize the uniqueness constraint name .
SELECT * FROM information_schema.table_constraints WHERE table_name = ' Table name '; # See what constraints are 
ALTER TABLE USER
DROP INDEX uk_name_pwd;

Be careful : Can pass show index from The name of the table ; # View the index of the table

4. PRIMARY KEY constraint

1) effect

Used to uniquely identify a row of records in the table .

2) keyword

primary key

3) characteristic

A primary key constraint is equivalent to a unique constraint + A combination of nonnull constraints , Primary key constraint columns are not allowed to be duplicate , Null values are not allowed .

  • A table can have at most one primary key constraint , You can create a primary key constraint at the column level , You can also create... At the table level .
  • The primary key constraint corresponds to one or more columns in the table ( Composite primary key )
  • If it is a multi column composite primary key constraint , Then none of these columns are allowed to be null , And the combined value is not allowed to repeat .
  • MySQL The primary key name of is always PRIMARY, Even if you name the primary key constraint name, it's useless .
  • When creating a primary key constraint , By default, the system will establish a corresponding primary key index on the column or column combination ( That can be queried according to the primary key , Query according to the primary key , More efficient . If the primary key constraint is deleted , The index corresponding to the primary key constraint is automatically deleted .
  • One thing to note is that , Do not modify the value of the primary key field . Because the primary key is the unique identification of the data record , If you modify the value of the primary key , It may destroy the integrity of the data .

4) Add primary key constraint

1. Specify the primary key constraint when creating the table

create table  The name of the table (
 Field name   data type  primary key, # Column level mode 
 Field name   data type ,
 Field name   data type 
);

create table  The name of the table (
 Field name   data type ,
 Field name   data type ,
 Field name   data type ,
[constraint  Constraint name ] primary key( Field name ) # Table level mode 
);

2. Add a primary key constraint after creating a table

ALTER TABLE  The name of the table  ADD PRIMARY KEY( Field list ); # The field list can be a field , It can also be multiple fields , If there are multiple fields , The primary key is compound 

5) About composite primary keys

create table  The name of the table (
 Field name   data type ,
 Field name   data type ,
 Field name   data type ,
primary key( Field name 1, Field name 2) # Represents the field 1 And field 2 The combination is unique , You can also have more fields 
);

6) Delete primary key constraint

alter table  The name of the table  drop primary key

explain : Delete primary key constraint , You do not need to specify the primary key name , Because a table has only one primary key , After deleting the primary key constraint , Non empty still exists .

5. On the column :AUTO_INCREMENT

1) effect

The value of a field increases automatically

2) keyword

auto_increment

3) characteristic

(1) A table can only have at most one self growing column

(2) When a unique identifier or sequential value needs to be generated , Self growth can be set

(3) The column of the self growing column constraint must be a key column ( Primary key column , Unique key column )

(4) The data type of a column with a self increasing constraint must be an integer type

(5) If the auto increment column specifies 0 and null, It will automatically increase based on the current maximum ; If the auto increment column manually specifies a specific value , Direct assignment to a specific value .

4) How to specify self increasing constraints

1. Build table

create table  The name of the table (
 Field name   data type  primary key auto_increment,
 Field name   data type  unique key not null,
 Field name   data type  unique key,
 Field name   data type  not null default  The default value is ,
);
create table  The name of the table (
 Field name   data type  default  The default value is  ,
 Field name   data type  unique key auto_increment,
 Field name   data type  not null default  The default value is ,
primary key( Field name )
);

2. After the establishment of the table

alter table  The name of the table  modify  Field name   data type  auto_increment;

5) Delete autoincrement constraint

#alter table  The name of the table  modify  Field name   data type  auto_increment;# Add a self increasing constraint to this field 
alter table  The name of the table  modify  Field name   data type ; # Get rid of auto_increment It is equivalent to deleting 

6) MySQL 8.0 New characteristics — Persistence of self increasing variables

stay MySQL 8.0 Before , Since the primary key AUTO_INCREMENT If the value of is greater than max(primary key)+1, stay MySQL After restart , Reset AUTO_INCREMENT=max(primary key)+1, In some cases, this phenomenon may lead to business primary key conflict or other difficult to find problems . The following is a case to compare whether self increasing variables in different versions are persistent . stay MySQL 5.7 In the version , The test steps are as follows Next : The created data table contains self incrementing primary keys id Field , The statement is as follows :

CREATE TABLE test1(
id INT PRIMARY KEY AUTO_INCREMENT
);

stay MySQL 5.7 In the system , For the allocation rule of self increasing primary key , By InnoDB The data dictionary One inside Counter To decide , And the counter is only in In memory maintenance , It doesn't persist to disk . When the database restarts , The The counter will be initialized .

stay MySQL 8.0 Persist the counter of self incrementing primary key to Redo log in . Every time the counter changes , Will be written to the redo log in . If the database restarts ,InnoDB The memory value of the counter will be initialized according to the information in the redo log .

6. FOREIGN KEY constraint

1) effect

Limit the referential integrity of a field in a table .

2) keyword

FOREIGN KEY

3) Master and slave tables / Parent and child tables

Main table ( Parent table ): The cited table , The referenced table

From the table ( Sub table ): Quote someone else's table , Refer to other people's tables

4) characteristic

(1) From the foreign key column of the table , Must quote / Refer to the primary key of the main table or the column with unique constraint ? Because of being dependent / The referenced value must be unique

(2) When creating a foreign key constraint , If you don't name the foreign key constraint , The default name is not a column name , Instead, it automatically generates a foreign key name ( for example student_ibfk_1;), You can also specify a foreign key constraint name .

(3) establish (CREATE) If you specify a foreign key constraint when using the table , Create the main table first , Then create the slave table

(4) When deleting a table , Delete from the table first ( Or delete the foreign key constraint first ), Delete the main table

(5) When the records of the master table are referenced from the slave table , Records in the main table will not be allowed to be deleted , If you want to delete data , You need to delete the data that depends on this record from the table first , Then you can delete the data of the main table

(6) stay “ From the table ” Specify foreign key constraints in , And a table can establish multiple foreign key constraints

(7) The foreign key column of the slave table and the column name of the main table can be different , But the data type must be the same , The logical meaning is consistent . If the types are different , When creating a child table , There will be errors “ERROR 1005 (HY000): Can’t create table’database.tablename’(errno: 150)”. for example : They all represent the department number , All are int type .

(8) When creating a foreign key constraint , By default, the system will establish the corresponding common index on the column . But the index name is the constraint name of the foreign key .( It is very efficient to query according to foreign keys )

(9) After deleting the foreign key constraint , The corresponding index must be manually deleted

5) Add a foreign key constraint

1. Build table

create table  Main table name (
 Field 1  data type  primary key,
 Field 2  data type 
);

create table  From table name (
 Field 1  data type  primary key,
 Field 2  data type ,
[CONSTRAINT < Foreign key constraint name >] FOREIGN KEY( From a field in the table ) references  Main table name ( Referenced field )
);
#( From a field in the table ) The data type of must be the same as the main table name ( Referenced field ) The data types of are consistent , The logical meaning is the same 
#( From a field in the table ) The field name can be the same as the main table name ( Referenced field ) The field name of is the same , It can be different 
-- FOREIGN KEY:  Specify the columns in the child table at the table level 
-- REFERENCES:  Columns marked in the parent table 
create table dept( # Main table 
did int primary key, # Department number 
dname varchar(50) # Department name 
);
create table emp(# From the table 
eid int primary key, # Employee number 
ename varchar(5), # Employee name 
deptid int, # The employee's Department 
foreign key (deptid) references dept(did) # Specify the foreign key constraint from the table 
#emp Tabular deptid And dept Tabular did The data types of are consistent , The meaning is the number of the Department 
);
 explain :
(1) Main table dept You must create it successfully first , Then you can create emp surface , Foreign key specified successfully .
(2) When deleting a table , First delete from table emp, Delete the main table dept

2. After the establishment of the table

In general , Table and table associations are designed in advance , therefore , The foreign key constraint will be defined when creating the table . No too , If you need to modify the design of the table ( For example, add a new field , Add new relationships ), But there are no predefined foreign key constraints , that Well , We need to modify the table to supplement the definition .

Format :

ALTER TABLE  From the table name  ADD [CONSTRAINT  Constraint name ] FOREIGN KEY ( From the fields of the table ) REFERENCES  Main table name ( Referenced fields ) [on update xx][on delete xx];

give an example :

ALTER TABLE emp1
ADD [CONSTRAINT emp_dept_id_fk] FOREIGN KEY(dept_id) REFERENCES dept(dept_id);

6) Constraint level

  • Cascade The way : On parent table update/delete When recording , Sync update/delete Drop matching records of child tables
  • Set null The way : On parent table update/delete When recording , Set the column of the matching record on the child table to null, But be careful The foreign key column of the table cannot be not null
  • No action The way : If there are matching records in the sub table , The parent table is not allowed to correspond to the candidate key update/delete operation
  • Restrict The way : Same as no action, Check foreign key constraints immediately
  • Set default The way ( In visualization tools SQLyog May be blank in ): When the parent table changes , The sub table sets the foreign key column to Into a default value , but Innodb Can't identify x

If no level is specified , Equivalent to Restrict The way . For foreign key constraints , It's better to use : ON UPDATE CASCADE ON DELETE RESTRICT The way .

7) Delete foreign key constraint

The process is as follows :

(1) The first step is to view the constraint name and delete the foreign key constraint 
SELECT * FROM information_schema.table_constraints WHERE table_name = ' The name of the table ';  # View the constraint name of a table 
ALTER TABLE  From the table name  DROP FOREIGN KEY  Foreign key constraint name ;

(2) The second step is to view the index name and delete the index .( Be careful , You can only manually delete )
SHOW INDEX FROM  The name of the table ; # View the index name of a table 
ALTER TABLE  From the table name  DROP INDEX  Index name ;

8) Development scenarios

problem 1: If there is a relationship between two tables ( one-on-one 、 One to many ), such as : Employee table and department table ( One to many ), Whether there is... Between them Be sure to create foreign key constraints ?

answer : No, it isn't

problem 2: What is the difference between building and not building foreign key constraints ?

answer : Foreign key constraint , Your operation ( Create table 、 Delete table 、 add to 、 modify 、 Delete ) Will be limited , Grammatically limited system . for example : It is impossible to add an employee information in the employee table , The value of its department cannot be found in the Department table .

No foreign key constraints , Your operation ( Create table 、 Delete table 、 add to 、 modify 、 Delete ) There is no limit on the , To ensure the accuracy of the data Reference integrity sex , Only rely on the programmer's consciousness , Or is it stay Java Define in the program . for example : In the employee list , You can add an employee's Information , Its department is designated as a completely non-existent Department .

problem 3: So is there a relationship between building or not building foreign key constraints and queries ?

answer : No,

stay MySQL in , Foreign key constraints are costly , Need to consume system resources . For large concurrent SQL operation , It may not be suitable for . For example, the central database of large websites , It may become very slow due to the overhead of foreign key constraints . therefore , MySQL Allows you not to use the system's own foreign key constraints , stay Application level Complete the logic of checking data consistency . in other words , Even if you don't Constrain with foreign keys , We should also find ways to use additional logic at the application level , To implement the function of foreign key constraints , Ensure data consistency .

9) Ali Development Specification

【 mandatory 】 Do not use foreign keys and cascades , All foreign key concepts must be solved in the application layer .

explain :( Conceptual explanation ) In the student list student_id It's the primary key , So the student_id Foreign key . If we learn to update In the table student_id, Also trigger the student_id to update , That's cascading updates . Foreign keys and cascading updates apply to single Low concurrency , Not suitable for Distributed 、 High concurrency cluster ; Cascading updates are strong blocking , There is a database Update storm The risk of ; Foreign keys affect Database Insertion speed .

7. CHECK constraint

1) effect

Check whether the value of a field is a symbol xx requirement , Generally refers to the range of values

2) keyword

CHECK

3) explain

MySQL5.7 have access to check constraint , but check Constraints have no effect on Data Validation . When adding data , There are no errors or warnings

however MySQL 8.0 Can be used in check Constrained .

create table employee(
eid int primary key,
ename varchar(5),
gender char check (' male ' or ' Woman ')
);

8. DEFAULT constraint

1) effect

Give a field / Specify a default value for a column , Once the default value is set , When inserting data , If this field has no explicit assignment , The default value is assigned .

2) keyword

DEFAULT

3) Add default

1. Build table

create table  The name of the table (
 Field name   data type  primary key,
 Field name   data type  unique key not null,
 Field name   data type  unique key,
 Field name   data type  not null default  The default value is ,
);

2. After the establishment of the table

alter table  The name of the table  modify  Field name   data type  default  The default value is ;
# If this field had a non NULL constraint , You also keep non empty constraints , Then when adding the default value constraint , You have to keep the non NULL constraint , Otherwise, the non empty constraint will be deleted 
# Empathy , The same is true when you add a non NULL constraint to a field , If this field had a default value constraint , You want to keep , Also in modify Keep the default value constraint in the statement , Otherwise, it will be deleted 
alter table  The name of the table  modify  Field name   data type  default  The default value is  not null;

Delete default

alter table  The name of the table  modify  Field name   data type ; # Delete default constraint , Non null constraints are not retained 
alter table  The name of the table  modify  Field name   data type  not null; # Delete default constraint , Keep non empty constraints 

9. interview

interview 1、 Why is it that when creating tables , Add not null default ‘’ or default 0

answer : Don't want to appear in the table null value .

interview 2、 Why don't you want null Value

answer :

(1) Bad comparison .null Is a special value , You can only use special is null and is not null To compare . Encountered operator , through Constant return null.

(2) The efficiency is not high . Affect and improve the index effect . therefore , When we are building tables not null default ‘’ or default 0

interview 3、 belt AUTO_INCREMENT The field value of the constraint is from 1 Did you start ?

stay MySQL in , Default AUTO_INCREMENT Initial The value is 1, Every new record , The field value is automatically added 1. Set auto increment properties (AUTO_INCREMENT) When , You can also specify a second The value of the auto increment field of an inserted record , In this way, the auto increment field value of the newly inserted record increases from the initial value , For example, insert the first... In the table Bar record , At the same time specified id The value is 5, Then the record to be inserted later id The value will change from 6 Begin to increase . When adding a primary key constraint , Often need to The field is automatically set .

interview 4、 Not every table can choose any storage engine ?

Foreign key constraints (FOREIGN KEY) Can't be used across engines .

MySQL Support for multiple storage engines , Each table can specify a different storage engine , It should be noted that : Foreign key constraints are used to To ensure the referential integrity of data , If you need to associate foreign keys between tables , Different storage engines are specified , So there is no difference between these tables Can create foreign key constraints . So , The choice of storage engine is not completely arbitrary .

The first 14 Chapter _ View

1. Common database objects

object describe
surface (TABLE) A table is a logical unit that stores data , Exist as rows and columns , Columns are fields , Line is the record
The data dictionary Is the system table , A table that holds database related information . The data of the system table is usually maintained by the database system , Programmers usually shouldn't modify , You can only view
constraint (CONSTRAINT) Rules for performing data verification , Rules for ensuring data integrity
View (VIEW) Logical display of data in one or more datasheets , Views do not store data
Indexes (INDEX) Used to improve query performance , It's equivalent to a book catalog
stored procedure (PROCEDURE) Used to complete a complete business process , no return value , However, multiple values can be passed to the caller through outgoing parameters Use environment
Storage function (FUNCTION) Used to complete a specific calculation , Has a return value
trigger (TRIGGER) It's like an event listener , When a specific event occurs in the database , Trigger is triggered , Complete the corresponding processing

2. View overview

  • View is a kind of Virtual table , Itself is No data Of , Takes up very little memory space , It is SQL An important concept in .
  • Views are built on existing tables , The tables on which the view is built are called base tables .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-u1fPoMN7-1655907404979)(MySQL The basic chapter .assets/image-20220608173721188.png)]

  • The creation and deletion of views only affect the view itself , It does not affect the corresponding base table . But when the data in the view is added 、 Delete and When modifying operations , The data in the data table will change accordingly , vice versa .
  • The statement that the view provides data content is SELECT sentence , Views can be understood as stored SELECT sentence
    • In the database , The view does not save data , The data is really saved in the data table . When adding data to the view 、 Delete When removing and modifying operations , The data in the data table will change accordingly ; vice versa .
  • View , Is another form of providing users with base table data . Usually , The database of small projects can not be used chart , But on big projects , And when the data table is complex , The value of view is highlighted , It can help me We put the result set of frequent queries into the virtual table , Improve efficiency . It is very convenient to understand and use .

3. Create view

  • stay CREATE VIEW Insert subquery in statement
CREATE [OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
VIEW  View name  [( Field list )]
AS  Query statement 
[WITH [CASCADED|LOCAL] CHECK OPTION]
  • Lite version
CREATE VIEW  View name 
AS  Query statement 

1) Create a single table view

give an example :

#  Mode one :
CREATE VIEW empvu80
AS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 80;

#  Mode two :
CREATE VIEW empsalary8000(emp_id, NAME, monthly_sal) #  The number of fields in parentheses is the same as SELECT The number of fields in the is the same 
AS
SELECT employee_id, last_name, salary
FROM employees
WHERE salary > 8000;

Query view :

SELECT *
FROM salvu80;

2) Create a multi table union view

give an example :

CREATE VIEW empview
AS
SELECT employee_id emp_id,last_name NAME,department_name
FROM employees e,departments d
WHERE e.department_id = d.department_id;
CREATE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS
SELECT d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary)
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name;
  • Use the view to format the data

It is often necessary to output content in a certain format , For example, we want to output the employee name and the corresponding department name , The corresponding format is emp_name(department_name), You can use the view to complete the operation of data formatting :

CREATE VIEW emp_depart
AS
SELECT CONCAT(last_name,'(',department_name,')') AS emp_dept
FROM employees e JOIN departments d
WHERE e.department_id = d.department_id;

3) Create a view based on the view

When we create a view , You can also continue to create views on top of it .

give an example : union “emp_dept” The view and “emp_year_salary” View query employee name 、 Department name 、 Annual salary information creation “emp_dept_ysalary” View .

CREATE VIEW emp_dept_ysalary
AS
SELECT emp_dept.ename,dname,year_salary
FROM emp_dept INNER JOIN emp_year_salary
ON emp_dept.ename = emp_year_salary.ename;

4. View view

grammar 1: View the table objects of the database 、 View objects

SHOW TABLES;

grammar 2: Look at the structure of the view

DESC / DESCRIBE  View name ;

grammar 3: View the attribute information of the view

#  View view information ( Display the storage engine of the data table 、 edition 、 Number of data rows and data size, etc )
SHOW TABLE STATUS LIKE ' View name '\G

Execution results show , notes Comment by VIEW, Explain that the table is a view , Other information is NULL, It means that this is a virtual table . grammar 4: View the detailed definition information of the view

SHOW CREATE VIEW  View name ;

5. Update data for view

1) General situation

MySQL Support use INSERT、UPDATE and DELETE Statement to insert data in a view 、 Update and delete operations . When in view When the data changes , The data in the data table will also change , vice versa .

give an example :UPDATE operation

UPDATE emp_tel SET tel = '13789091234' WHERE ename = ' Sun Hongliang ';

give an example :DELETE operation

 DELETE FROM emp_tel WHERE ename = ' Sun Hongliang ';

2) Non updatable views

To make the view updatable , There must be... Between the rows in the view and the rows in the underlying base table one-on-one The relationship between . In addition, when the view definition is as follows , View does not support update operation :

  • When defining the view, you specify “ALGORITHM = TEMPTABLE”, View will not support INSERT and DELETE operation ;
  • The view does not contain all columns in the base table that are defined as non empty and do not specify a default value , View will not support INSERT operation ;
  • In defining the SELECT Used in the statement JOIN The joint query , View will not support INSERT and DELETE operation ;
  • In defining the SELECT The field list after the statement uses Mathematical expression or Subquery , View will not support INSERT, also I won't support it UPDATE Mathematical expressions are used 、 The field value of the subquery ;
  • In defining the SELECT Statement is used in the field list after the DISTINCT 、 Aggregate functions 、 GROUP BY 、 HAVING 、 UNION etc. , View will not support INSERT、UPDATE、DELETE;
  • In defining the SELECT Statement contains a subquery , The subquery refers to FROM The watch at the back , View will not support INSERT、UPDATE、DELETE;
  • The view definition is based on a Non updatable view ; Constant view .

Although view data can be updated , But on the whole , View as virtual table , It is mainly used to facilitate query , It is not recommended to update the data of the view . Changes to view data , It is done by operating the data in the actual data table .

6. modify 、 Delete view

1) Modify the view

The way 1: Use CREATE OR REPLACE VIEW Clause to modify the view

CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS
SELECT employee_id, first_name || ' ' || last_name, salary, department_id
FROM employees
WHERE department_id = 80;

explain :CREATE VIEW The alias of each column in the clause should correspond to each column in the subquery .

The way 2:ALTER VIEW

The syntax for modifying a view is :

ALTER VIEW  View name 
AS
 Query statement 

2) Delete view

  • Deleting a view just deletes the definition of the view , The data of the base table will not be deleted .
  • The syntax for deleting a view is :
DROP VIEW IF EXISTS  View name ;
  • give an example :
DROP VIEW empvu80;
  • explain : View based a、b Created a new view c, If the view a Or view b Delete , Will cause the view c Your query failed . this Sample view c Need to manually delete or modify , Otherwise, it will affect the use of .

7. summary

1) advantage

1. It's easy to operate

Define frequently used query operations as views , It can make developers do not need to care about the structure of the data table corresponding to the view 、 The relationship between tables , There is no need to care about the business logic and query conditions between data tables , Simply manipulate the view , It greatly simplifies the operation of developers on the database .

2. Reduce data redundancy

The view is different from the actual data table , It stores query statements . therefore , In use , We need to define the query language of the view Sentence to get the result set . The view itself does not store data , Do not occupy the resources of data storage , Reduced data redundancy .

3. Data security

MySQL The user's response to the data Access restrictions On the result set of some data , The result set of these data can be realized by using views . use Users do not have to query or operate the data table directly . This can also be understood as the view has Isolation, . The view is equivalent to adding a layer of virtual tables between the user and the actual data table .

meanwhile ,MySQL Users' access to data can be restricted to some views according to their permissions , Users do not need to query the data table , The information in the data table can be obtained directly through the view . This ensures the security of the data in the data table to a certain extent .

4. Adapt to flexible needs

When the requirements of the business system change , If you need to change the structure of the data table , The workload is relatively Big , You can use views to reduce the amount of change . This method is often used in practical work .

5. Ability to decompose complex query logic

If there is complex query logic in the database , Then the problem can be decomposed , Create multiple views get data , Then combine the created multiple views , Complete complex query logic .

2) Insufficient

If we create a view based on the actual data table , that , If the structure of the actual data table changes , We need to maintain the relevant views in time . Especially nested views ( Is to create a view based on the view ), Maintenance will become more complex , Poor readability , It can easily become a potential hidden danger of the system . Because the view is created SQL Queries may rename fields , It may also contain complex logic , These will increase the cost of maintenance .

In actual projects , If there are too many views , It will lead to the problem of database maintenance cost .

therefore , When creating views , You should combine the actual project needs , Comprehensively consider the advantages and disadvantages of view , In this way, the view can be used correctly , Make the whole system optimal .

The first 15 Chapter _ Stored procedures and functions

MySQL from 5.0 The version began to support stored procedures and functions . Stored procedures and functions can transform complex SQL Logic encapsulated together , Applications It doesn't need to pay attention to the internal complexity of stored procedures and functions SQL Logic , You just need to simply call stored procedures and functions .

1. Overview of stored procedures

1) understand

** meaning :** The English of stored procedure is Stored Procedure . Its idea is very simple , It's just a group of people passing through Precompiled SQL sentence Encapsulation .

Execution process : Stored procedures are pre stored in MySQL Server , When it needs to be implemented , The client only needs to issue a command to the server to call the stored procedure , The server side can store the pre stored series SQL Execute all statements .

benefits :

  • 1、 Simplified operation , Improved sql Statement reusability , Reduce the pressure on developers .
  • 2、 Reduce errors in operation , Increase of efficiency .
  • 3、 Reduce network traffic ( The client does not need to put all SQL The statement is sent to the server through the network ).
  • 4、 Less SQL The statement is exposed to Online risks , It also improves the security of data query .

And views 、 Comparison of functions :

It has the same advantages as view , Clear 、 Security , It can also reduce the amount of network transmission . But it's different from the view , Views are virtual tables , Usually do not directly operate on the underlying data table , And stored procedures are programmed SQL, Sure Directly operate the underlying data table , Compared with the collection oriented operation , It can realize some more complex data processing .

Once the stored procedure is created , Using it is as simple as using a function , We can just call the stored procedure name directly . Compared to the function , The stored procedure is no return value Of .

2) classification

The parameter type of the stored procedure can be IN、OUT and INOUT. According to this classification is as follows :

1、 No parameters ( No parameters, no return )

2、 Just bring IN type ( No return with parameters )

3、 Just bring OUT type ( No parameters return )

4、 With both IN And bring OUT( There are parameters and returns )

5、 belt INOUT( There are parameters and returns )

Be careful :IN、OUT、INOUT You can take more than one in one stored procedure .

2. Create stored procedure

1) Syntax analysis

grammar :

CREATE PROCEDURE  Stored procedure name (IN|OUT|INOUT  Parameter name   Parameter type ,...)
[characteristics ...]
BEGIN
 Stored procedure body 
END

explain :

1、 The meaning of the symbol before the parameter

  • IN : The current parameter is the input parameter , That is to say, the input parameter ;

    The stored procedure just reads the value of this parameter . If no parameter type is defined , The default is IN , Represents input parameter .

  • OUT : The current parameter is the output parameter , That is to say, it shows that ;

    After the execution is complete , The client or application calling the stored procedure can read the value returned by the parameter .

  • INOUT : The current parameter can be either an input parameter , It can also be an output parameter .

2、 The formal parameter type can be MySQL Any type in the database .

3、characteristics Represents the constraint on the stored procedure specified when creating the stored procedure , The value information is as follows :

LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
  • LANGUAGE SQL : Note that the stored procedure execution body is composed of SQL The sentences make up , The languages supported by the current system are SQL.

  • [NOT] DETERMINISTIC : Indicates whether the result of the stored procedure execution is determined .DETERMINISTIC Indicates that the result is certain Of . Every time a stored procedure is executed , The same input gets the same output .NOT DETERMINISTIC Indicates that the result is uncertain Of , The same input may get different outputs . If no value is specified , The default is NOT DETERMINISTIC.

  • { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } : Indicates that the subroutine makes use SQL Sentence restrictions .

    • CONTAINS SQL Indicates that the subroutine of the current stored procedure contains SQL sentence , But it doesn't contain read-write data SQL sentence ;
    • NO SQL Indicates that the subroutine of the current stored procedure does not contain any SQL sentence ;
    • READS SQL DATA Indicates that the subroutine of the current stored procedure contains read data SQL sentence ;
    • MODIFIES SQL DATA Indicates that the subroutine of the current stored procedure contains data to be written SQL sentence .
    • By default , The system specifies as CONTAINS SQL.
  • SQL SECURITY { DEFINER | INVOKER } : Permission to execute the current stored procedure , That is, it indicates which users can execute the current stored procedure .

    • DEFINER Indicates that only the creator or definer of the current stored procedure can execute the current stored procedure ;
    • INVOKER Indicates that a user with access to the current stored procedure can execute the current stored procedure .
  • COMMENT ‘string’ : Annotation information , Can be used to describe stored procedures .

4、 There can be more than one in the stored procedure body SQL sentence , If only one SQL sentence , You can omit BEGIN and END

1. BEGIN…END:BEGIN…END  There are multiple statements in the middle , Each statement starts with (;) The sign is the Terminator .
2. DECLARE:DECLARE  Used to declare variables , The position of use is  BEGIN…END  In the middle of the sentence , And it needs to be used before other statements 
 Declaration of line variables .
3. SET: Assignment statement , Used to assign values to variables .
4. SELECT… INTO: Store the query results from the data table into variables , That is, assign values to variables .

5、 You need to set a new end tag

DELIMITER  New end tag 

because MySQL The default statement end symbol is semicolon ‘;’. To avoid problems with stored procedures SQL Statement terminator conflicts , Need to use DELIMITER Changes the end of a stored procedure .

such as :“DELIMITER //” The statement will MySQL Is set to //, And “END //” End stored procedure . Store process settings Use after righteousness is finished “DELIMITER ;” Restore the default Terminator .DELIMITER You can also specify other symbols as endings .

When using DELIMITER On command , Backslashes should be avoided (‘\’) character , Because the backslash is MySQL The escape character of .

Example :

DELIMITER $
CREATE PROCEDURE  Stored procedure name (IN|OUT|INOUT  Parameter name   Parameter type ,...)
[characteristics ...]
BEGIN
sql sentence 1;
sql sentence 2;
END $

2) The code for

give an example 1: Create stored procedure select_all_data(), see emps All data of table

DELIMITER $
CREATE PROCEDURE select_all_data()
BEGIN
SELECT * FROM emps;
END $
DELIMITER ;

give an example 2: Create stored procedure avg_employee_salary(), Return the average salary of all employees

DELIMITER //
CREATE PROCEDURE avg_employee_salary ()
BEGIN
SELECT AVG(salary) AS avg_salary FROM emps;
END //
DELIMITER ;

3. Calling stored procedure

1) Invocation format

Stored procedures have a variety of calling methods . Stored procedures must use CALL The statement calls , And the stored procedure is related to the database , If you want to execute stored procedures in other databases , You need to specify a database name , for example CALL dbname.procname.

CALL  Stored procedure name ( Argument list )

Format :

1、 call in Parameters of the pattern :

CALL sp1(' value ');

2、 call out Parameters of the pattern :

SET @name;
CALL sp1(@name);
SELECT @name;

3、 call inout Parameters of the pattern :

SET @name= value ;
CALL sp1(@name);
SELECT @name;

2) The code for

give an example 1:

DELIMITER //
CREATE PROCEDURE CountProc(IN sid INT,OUT num INT)
BEGIN
SELECT COUNT(*) INTO num FROM fruits
WHERE s_id = sid;
END //
DELIMITER ;

Calling stored procedure :

CALL CountProc (101, @num);

View return results :

SELECT @num;

** give an example 2:** Create stored procedure , Realize accumulation operation , Calculation 1+2+…+n How much . The specific code is as follows :

DELIMITER //
CREATE PROCEDURE `add_num`(IN n INT)
BEGIN
DECLARE i INT;
DECLARE sum INT;
SET i = 1;
SET sum = 0;
WHILE i <= n DO
SET sum = sum + i;
SET i = i +1;
END WHILE;
SELECT sum;
END //
DELIMITER ;

Use it directly CALL add_num(50); that will do . The parameter I passed in here is 50, That is statistics 1+2+…+50 The sum of accumulation .

3) How to debug

stay MySQL in , Stored procedures are not like ordinary programming languages ( such as VC++、Java etc. ) There is a special integrated development environment . because this , You can go through SELECT sentence , Query the intermediate results of program execution , To debug a SQL Statement correctness . debugging After success , hold SELECT Move to the next... After the statement SQL After statement , Debug the next SQL sentence . such Step by step , You can complete the debugging of all operations in the stored procedure . Of course , You can also put... In a stored procedure SQL Copy the statement , Separate section by section debugging .

4. Use of storage function

1) Syntax analysis

The functions I've learned :LENGTH、SUBSTR、CONCAT etc.

Grammar format :

CREATE FUNCTION  Function name ( Parameter name   Parameter type ,...)
RETURNS  return type 
[characteristics ...]
BEGIN
 The body of the function  # There must be... In the body of the function  RETURN  sentence 
END

explain :

1、 parameter list : The specified parameter is IN、OUT or INOUT Only right PROCEDURE It's legal. ,FUNCTION It always defaults to IN Parameters .

2、RETURNS type Statement represents the type of data returned by the function ; RETURNS Clause can only be used for FUNCTION Make a designation , For functions, this is mandatory Of . It is used to specify the return type of the function , And letter The number body must contain a RETURN value sentence .

3、characteristic The constraint on the function specified when creating the function . The value is the same as when creating the stored procedure , No more details here .

4、 The function body can also be used BEGIN…END To express SQL The beginning and end of the code . If the function body has only one statement , You can omit it BEGIN…END.

2) Calling the storage function

stay MySQL in , How to use the storage function is the same as MySQL The use of internal functions is the same . In other words , User defined storage functions and MySQL The internal function is a property . The difference lies in , The storage function is User defined Of , And the inner function is MySQL Of Developer definition Of .

SELECT  Function name ( Argument list )

3) The code for

give an example 1:

Create a storage function , The name is email_by_name(), Parameter definition is null , This function queries Abel Of email, And back to , The data type is string .

DELIMITER //
CREATE FUNCTION email_by_name()
RETURNS VARCHAR(25)
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT email FROM employees WHERE last_name = 'Abel');
END //
DELIMITER ;

call :

SELECT email_by_name();

give an example 2:

Create a storage function , The name is email_by_id(), Parameters of the incoming emp_id, This function queries emp_id Of email, And back to , data type Is string type .

DELIMITER //
CREATE FUNCTION email_by_id(emp_id INT)
RETURNS VARCHAR(25)
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT email FROM employees WHERE employee_id = emp_id);
END //
DELIMITER ;

call :

SET @emp_id = 102;
SELECT email_by_id(@emp_id);

Be careful :

If an error is reported in creating a storage function “ you might want to use the less safe log_bin_trust_function_creators variable ”, There are two ways to deal with it :

  • The way 1:

    Add the necessary functional features “[NOT] DETERMINISTIC” and “{CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA}”

  • The way 2:

SET GLOBAL log_bin_trust_function_creators = 1;

4) Compare stored functions with stored procedures

keyword Call syntax Return value Application scenarios
stored procedure PROCEDURECALL stored procedure () Understanding for 0 One or more Generally used for updating
Storage function FUNCTIONSELECT function () It can only be one Generally used when the query result is a value and returned

Besides , Storage functions can be used in query statements , Stored procedures don't work . conversely , Stored procedures are more powerful , Including the ability to Perform operations on the table ( For example, create a table , Delete tables, etc ) And transaction operations , These functions are not available in storage functions .

5. View of stored procedures and functions 、 modify 、 Delete

1) see

After creation , How do we know the stored procedure we created 、 Is the storage function successful ?

MySQL It stores the state information of stored procedures and functions , Users can use SHOW STATUS Sentence or SHOW CREATE Sentence see , It can also be directly from the... Of the system information_schema Query in database . Here are 3 Methods .

  1. Use SHOW CREATE Statement to view the creation information of stored procedures and functions
SHOW CREATE {PROCEDURE | FUNCTION}  Stored procedure name or function name 
  1. Use SHOW STATUS Statement to view the status information of stored procedures and functions
SHOW {PROCEDURE | FUNCTION} STATUS [LIKE 'pattern']
  1. from information_schema.Routines View the information of stored procedures and functions in the table

MySQL The information of stored procedures and functions is stored in information_schema Database based Routines In the table . You can query the information of stored procedures and functions by querying the records of the table . Its basic grammatical form is as follows :

SELECT * FROM information_schema.Routines
WHERE ROUTINE_NAME=' The name of a stored procedure or function ' [AND ROUTINE_TYPE = {'PROCEDURE|FUNCTION'}];

explain : If in MySQL The stored procedure and function names are the same in the database , It's better to designate ROUTINE_TYPE Query criteria to Indicates whether the query is a stored procedure or a function .

2) modify

Modify stored procedures or functions , Does not affect stored procedure or function functions , Just modify the relevant features . Use ALTER Statements for .

ALTER {PROCEDURE | FUNCTION}  The name of a stored procedure or function  [characteristic ...]

among ,characteristic Specify the properties of the stored procedure or function , Its value information is the same as that of creating a stored procedure 、 The value information of function is slightly different .

{ CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
  • CONTAINS SQL , Indicates that the subroutine contains SQL sentence , But does not contain statements that read or write data .

  • NO SQL , Indicates that the subroutine does not contain SQL sentence .

  • READS SQL DATA , A statement that contains read data in a subroutine .

  • MODIFIES SQL DATA , Represents a statement in a subroutine that contains data to be written .

  • SQL SECURITY { DEFINER | INVOKER } , Indicate who has authority to execute .

    • DEFINER , It means that only the definer himself can execute .
    • INVOKER , Indicates that the caller can execute .
  • COMMENT ‘string’ , Represents annotation information .

Modify stored procedures to use ALTER PROCEDURE sentence , Modify the storage function to use ALTER FUNCTION sentence . however , These two The structure of two statements is the same , All parameters in the statement are the same .

3) Delete

Deletes stored procedures and functions , have access to DROP sentence , The syntax is as follows :

DROP {PROCEDURE | FUNCTION} [IF EXISTS]  The name of a stored procedure or function 

6. Disputes over the use of stored procedures

1) advantage

1、 Stored procedures can be compiled and used more than once . Stored procedures are compiled only at creation time , There is no need to recompile later , That's a step up SQL Efficiency of execution .

2、 It can reduce the development workload . Put the code encapsulation Modular , It's actually one of the core ideas of programming , In this way, complex problems can be solved Disassemble into different modules , Then the modules can Reuse , While reducing development effort , It also ensures that the structure of the code is clear Clear .

3、 The security of stored procedure is strong . When setting up stored procedures, we can Set user permissions , This is the same as the view Strong security .

4、 It can reduce the amount of network transmission . Because the code is encapsulated in stored procedures , Each time you use it, you just need to call the stored procedure , That's less Less network traffic .

5、 Good encapsulation . When performing relatively complex database operations , We used to use one by one SQL sentence , You may want to connect Operations that can only be completed multiple times in the database , Now it's a stored procedure , It only needs Connect once .

2) shortcoming

Ali Development Specification 【 mandatory 】 Stored procedures are not allowed , Stored procedures are difficult to debug and extend , There is no portability .

1、 Poor portability . Stored procedures cannot be migrated across databases , For example MySQL、Oracle and SQL Server Stored in cheng , It needs to be rewritten when changing to other databases .

2、 Debugging difficulty . Only a few DBMS Supports debugging of stored procedures . For complex stored procedures , Development and maintenance are not allowed easy . Although there are some third-party tools that can debug stored procedures , But there's a charge .

3、 Version management of stored procedures is difficult . For example, the index of the data table has changed , Can cause stored procedures to fail . We are developing Version management is often required when using software , But the stored procedure itself has no version control , It's troublesome to update the version iteratively .

4、 It is not suitable for high concurrency scenarios . High concurrency scenarios need to reduce the pressure on the database , Sometimes the database will adopt the way of dividing database and table , And it's very scalable , under these circumstances , Stored procedures can become difficult to maintain , Increase the pressure on the database , Obviously not .

3) Summary

Stored procedures are convenient , There are limitations . Although different companies have different attitudes towards stored procedures , But for us developers , No matter what , Mastering stored procedures is one of the necessary skills .

The first 16 Chapter _ Variable 、 Process control and cursor

stay MySQL Stored procedures and functions in the database , Variables can be used to store intermediate result data of queries or calculations , Or output the final result data .

1. Variable

stay MySQL Stored procedures and functions in the database , Variables can be used to store intermediate result data of queries or calculations , Or output the final Results data for .

stay MySQL In the database , Variables are divided into System variables as well as User defined variables .

1) System variables

Classification of system variables

Variables are defined by the system , Not user defined , Belong to The server level . start-up MySQL service , Generate MySQL During the service instance , MySQL Will be for MySQL Assignment of system variables in server memory , These system variables define the current MySQL Properties of the service instance 、 , sign . The values of these system variables are either compile MySQL Time parameters The default value of , Or The configuration file ( for example my.ini etc. ) Parameters in value . You can use the website https://dev.mysql.com/doc/refman/8.0/en/server-systemvariables.html see MySQL The system variable of the document .

System variables are divided into global system variables ( Need to add global keyword ) And session system variables ( Need to add session keyword ), Sometimes global system variables are referred to as global variables , Sometimes the session system variable is also called local Variable . If you don't write , Default session level . Static variables ( stay MySQL Their values cannot be used while service instances are running set Dynamic modification ) Belongs to a special global system variable .

every last MySQL Client successfully connected MySQL After the server , Will produce the corresponding session . During the conversation ,MySQL The service instance will be in MySQL The session system variable corresponding to the session is generated in the server memory , The initial values of these session system variables are copies of the global system variable values . Here's the picture :

image-20220613135809104
  • The global system variable is for all sessions ( Connect ) It works , but Can't cross restart
  • The session system variable is only for the current session ( Connect ) It works . During the conversation , Modification of a session system variable value by the current session , It will not affect the value of the same session system variable in other sessions .
  • conversation 1 Modifying the value of a global system variable will cause the session to 2 Modification of the same global system variable value in .

stay MySQL Some system variables in can only be global , for example max_connections Used to limit the maximum number of connections to the server ; Some departments The scope of a system variable can be both global and session , for example character_set_client Character set used to set the client ; Some departments The scope of the system variable can only be the current session , for example pseudo_thread_id Used to mark the current session MySQL Connect ID.

Look at the system variables

  • View all or part of the system variables
# See all global variables 
SHOW GLOBAL VARIABLES;
# View all session variables 
SHOW SESSION VARIABLES;
 or 
SHOW VARIABLES;
# Look at some of the system variables that meet the criteria .
SHOW GLOBAL VARIABLES LIKE '% identifier %';
# Look at some session variables that meet the criteria 
SHOW SESSION VARIABLES LIKE '% identifier %';

View the specified system variable

As MySQL Coding standards ,MySQL The system variables in are expressed in Two “@” start , among “@@global” Used only to mark global system variables ,“@@session” Used only to mark the session system variable .“@@” First, mark the session system variable , If the session system variable does not exist , Then mark the global system variable .

# View the value of the specified system variable 
SELECT @@global. Variable name ;
# View the value of the specified session variable 
SELECT @@session. Variable name ;
# perhaps 
SELECT @@ Variable name ;

Modify the value of the system variable

Sometimes , The database administrator needs to modify the default value of the system variable , To modify the current session or MySQL Properties of the service instance 、 features . The specific methods :

The way 1: modify MySQL The configuration file , Then modify MySQL The value of the system variable ( This method needs to be restarted MySQL service )

The way 2: stay MySQL During service operation , Use “set” Command to reset the value of the system variable

# Assign a value to a system variable 
# The way 1:
SET @@global. Variable name = A variable's value ;
# The way 2:
SET GLOBAL  Variable name = A variable's value ;
# Assign a value to a session variable 
# The way 1:
SET @@session. Variable name = A variable's value ;
# The way 2:
SET SESSION  Variable name = A variable's value ;

2) User variables

User variable classification

User variables are defined by the user , As MySQL Coding standards ,MySQL The user variable in is represented by a “@” start . Depending on the scope of action , It is divided into Session user variables and local variable .

  • Session user variables : The scope is the same as the session variable , Only right Current connection Session valid .
  • local variable : Only in BEGIN and END Valid in statement block . Local variables can only be used in Stored procedures and functions Use in .

Session user variables

  • Definition of variables
# The way 1:“=” or “:=”
SET @ User variables  =  value ;
SET @ User variables  :=  value ;
# The way 2:“:=”  or  INTO keyword 
SELECT @ User variables  :=  expression  [FROM  Equal clause ];
SELECT  expression  INTO @ User variables  [FROM  Equal clause ];
  • Look at the value of the user variable ( see 、 Compare 、 Operations, etc )
SELECT @ User variables 

local variable

Definition : have access to DECLARE Statement defines a local variable

Scope : Just defining it BEGIN … END Effective in

Location : Only on the BEGIN … END in , And can only be placed in the first sentence

BEGIN
# Declare local variables 
DECLARE  Variable name 1  Variable data type  [DEFAULT  Variable defaults ];
DECLARE  Variable name 2, Variable name 3,...  Variable data type  [DEFAULT  Variable defaults ];
# Assign values to local variables 
SET  Variable name 1 =  value ;
SELECT  value  INTO  Variable name 2 [FROM  Clause ];
# View the value of a local variable 
SELECT  Variable 1, Variable 2, Variable 3;
END
  1. Defining variables
DECLARE  Variable name   type  [default  value ]; #  without DEFAULT Clause , The initial value is NULL
  1. Variable assignment

The way 1: Generally used to assign simple values

SET  Variable name = value ;
SET  Variable name := value ;

The way 2: It is generally used to assign field values in the table

SELECT  Field name or expression  INTO  Variable name  FROM  surface ;
  1. Using variables ( see 、 Compare 、 Operations, etc )
SELECT  Local variable name ;

give an example 1: Declare local variables , And assign the values to employees In the table employee_id by 102 Of last_name and salary

DELIMITER //
CREATE PROCEDURE set_value()
BEGIN
DECLARE emp_name VARCHAR(25);
DECLARE sal DOUBLE(10,2);
SELECT last_name, salary INTO emp_name,sal
FROM employees
WHERE employee_id = 102;
SELECT emp_name, sal;
END //
DELIMITER ;

give an example 2: Declare two variables , Sum and print ( Use session user variables separately 、 Local variables )

# The way 1: Use user variables 
SET @m=1;
SET @n=1;
SET @[email protected][email protected];
SELECT @sum;
# The way 2: Use local variables 
DELIMITER //
CREATE PROCEDURE add_value()
BEGIN
# local variable 
DECLARE m INT DEFAULT 1;
DECLARE n INT DEFAULT 3;
DECLARE SUM INT;
SET SUM = m+n;
SELECT SUM;
END //
DELIMITER ;

Compare session user variables with local variables

Scope Define the location grammar
Session user variables Current session Anywhere in the conversation Add @ Symbol , Don't specify type
local variable What defines it BEGIN END in BEGIN END The first sentence of Generally, there is no need to add @, Type required

2. Define conditions and handlers

Defined conditions It is to define the problems that may be encountered in the process of program execution in advance , The handler It defines how to deal with problems , And ensure that stored procedures or functions can continue to execute in case of warnings or errors . This can enhance the ability of the stored program to deal with problems , Avoid abnormal program stop .

explain : Define conditions and handlers in stored procedures 、 All storage functions are supported .

1) case analysis

case analysis : Create a name “UpdateDataNoCondition” Stored procedure . The code is as follows :

DELIMITER //
CREATE PROCEDURE UpdateDataNoCondition()
BEGIN
SET @x = 1;
UPDATE employees SET email = NULL WHERE last_name = 'Abel';
SET @x = 2;
UPDATE employees SET email = 'aabbel' WHERE last_name = 'Abel';
SET @x = 3;
END //
DELIMITER ;

Calling stored procedure :

mysql> CALL UpdateDataNoCondition();
ERROR 1048 (23000): Column 'email' cannot be null
mysql> SELECT @x;
+------+
| @x |
+------+
| 1 |
+------+
1 row in set (0.00 sec)

You can see , here @x The value of the variable is 1. In conjunction with creating stored procedures SQL Statement code can get : Condition not defined in stored procedure And the handler , And when the stored procedure executes SQL When the statement reports an error ,MySQL The database will throw an error , And exit the current SQL Logic , Don't go down .

2) Defined conditions

The defining condition is to give MySQL Error code naming in , This helps to make the stored program code clearer . It will be one Wrong name and designated Error condition Connect . This name can then be used to define the handler DECLARE HANDLER In the sentence .

Define conditional usage DECLARE sentence , The syntax is as follows :

DECLARE  Wrong name  CONDITION FOR  Error code ( Or wrong conditions )

Description of error code :

  • MySQL_error_code and sqlstate_value All of them can express MySQL Error of .
    • MySQL_error_code Is a numeric type error code .
    • sqlstate_value It's a length of 5 String type error code .

for example , stay ERROR 1418 (HY000) in ,1418 yes MySQL_error_code,'HY000’ yes sqlstate_value.

for example , stay ERROR 1142(42000) in ,1142 yes MySQL_error_code,'42000’ yes sqlstate_value.

give an example 1: Definition “Field_Not_Be_NULL” Wrong name and MySQL The type of error that violates a non NULL constraint in is “ERROR 1048 (23000)” Corresponding .

# Use MySQL_error_code
DECLARE Field_Not_Be_NULL CONDITION FOR 1048;
# Use sqlstate_value
DECLARE Field_Not_Be_NULL CONDITION FOR SQLSTATE '23000';

3) Define handler

It can be for SQL Some type of error that occurs during execution defines a special handler . When defining a handler , Use DECLARE sentence The grammar is as follows :

DECLARE  Processing mode  HANDLER FOR  Wrong type   Processing statements 
  • Processing mode : The treatment methods are 3 A value of :CONTINUE、EXIT、UNDO.

    • CONTINUE : Indicates that an error is encountered and will not be processed , Carry on .
    • EXIT : Exit immediately in case of an error .
    • UNDO : Indicates that the previous operation is withdrawn after an error is encountered .MySQL This operation is not supported in the .
  • Wrong type ( I.e. conditions ) It can be taken as follows :

    • SQLSTATE ‘ String error code ’ : The length is 5 Of sqlstate_value Error code for type ;
    • MySQL_error_code : Match numeric type error code ;
    • Wrong name : Express DECLARE … CONDITION Defined error condition name .
    • SQLWARNING : Match all to 01 At the beginning SQLSTATE Error code ;
    • NOT FOUND : Match all to 02 At the beginning SQLSTATE Error code ;
    • SQLEXCEPTION : Match all that have not been SQLWARNING or NOT FOUND The captured SQLSTATE Error code ;
  • Processing statements : If one of the above conditions occurs , The corresponding processing method is adopted , And execute the specified processing statement . The statement can be image “ SET Variable = value ” Such a simple statement , It can also be used BEGIN … END Write compound statements .

Several ways to define handlers , The code is as follows :

# Method 1: Capture sqlstate_value
DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' SET @info = 'NO_SUCH_TABLE';
# Method 2: Capture mysql_error_value
DECLARE CONTINUE HANDLER FOR 1146 SET @info = 'NO_SUCH_TABLE';
# Method 3: Define the conditions first , Call again 
DECLARE no_such_table CONDITION FOR 1146;
DECLARE CONTINUE HANDLER FOR NO_SUCH_TABLE SET @info = 'NO_SUCH_TABLE';
# Method 4: Use SQLWARNING
DECLARE EXIT HANDLER FOR SQLWARNING SET @info = 'ERROR';
# Method 5: Use NOT FOUND
DECLARE EXIT HANDLER FOR NOT FOUND SET @info = 'NO_SUCH_TABLE';
# Method 6: Use SQLEXCEPTION
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @info = 'ERROR';

4) Case solving

In the stored procedure , Define handler , Capture sqlstate_value value , When you meet MySQL_error_code The value is 1048 when , perform CONTINUE operation , And will @proc_value Is set to -1.

DELIMITER //
CREATE PROCEDURE UpdateDataNoCondition()
BEGIN
    # Define handler 
    DECLARE CONTINUE HANDLER FOR 1048 SET @proc_value = -1;
    SET @x = 1;
    UPDATE employees SET email = NULL WHERE last_name = 'Abel';
    SET @x = 2;
    UPDATE employees SET email = 'aabbel' WHERE last_name = 'Abel';
    SET @x = 3;
END //
DELIMITER ;

3. Process control

It is impossible to solve complex problems through a SQL Sentence completion , We need to perform multiple SQL operation . The function of process control statement is to control In the system storage process SQL The order in which statements are executed , Is an essential part of our complex operations . As long as the program is executed , Processes are divided into three categories :

  • Sequential structure : The program runs from top to bottom
  • Branching structure : The program is selected and executed according to conditions , Select one of two or more paths to execute
  • Loop structure : When the program meets certain conditions , Repeat a set of statements

Aim at MySQL The main flow control statements are 3 class . Be careful : Can only be used to store programs .

  • Conditional statements :IF Statement and CASE sentence
  • Loop statement :LOOP、WHILE and REPEAT sentence
  • Jump statements :ITERATE and LEAVE sentence

1) Branching structure IF

  • IF The grammatical structure of the statement is :
IF  expression 1 THEN  operation 1
[ELSEIF  expression 2 THEN  operation 2]……
[ELSE  operation N]
END IF

The result of the expression is TRUE or FALSE Execute the corresponding statement . here “[]” The content in is optional .

  • characteristic :① Different expressions correspond to different operations ② Use in begin end in

  • give an example 1:

IF val IS NULL
	THEN SELECT 'val is null';
ELSE SELECT 'val is not null';
END IF;
  • give an example 2: Declaring stored procedures “update_salary_by_eid1”, Definition IN Parameters emp_id, Enter employee number . Judge if the employee's salary is lower than 8000 Yuan and has been employed for more than 5 year , Just raise your salary 500 element ; Otherwise, it will remain the same .
DELIMITER //
CREATE PROCEDURE update_salary_by_eid1(IN emp_id INT)
BEGIN
    DECLARE emp_salary DOUBLE;
    DECLARE hire_year DOUBLE;
    SELECT salary INTO emp_salary FROM employees WHERE employee_id = emp_id;
    SELECT DATEDIFF(CURDATE(),hire_date)/365 INTO hire_year
    FROM employees WHERE employee_id = emp_id;
    IF emp_salary < 8000 AND hire_year > 5
    THEN UPDATE employees SET salary = salary + 500 WHERE employee_id = emp_id;
    END IF;
END //
DELIMITER ;

2) Branching structure CASE

  • CASE The grammatical structure of a sentence 1:
# Situation 1 : Be similar to switch
CASE  expression 
WHEN  value 1 THEN  result 1 Or words 1( If it's a statement , Need semicolon )
WHEN  value 2 THEN  result 2 Or words 2( If it's a statement , Need semicolon )
...
ELSE  result n Or words n( If it's a statement , Need semicolon )
END [case]( If it's on begin end Need to add case, If you put it in select There is no need for )
  • CASE The grammatical structure of a sentence 2:
# Situation two : Similar to multiple if
CASE
WHEN  Conditions 1 THEN  result 1 Or words 1( If it's a statement , Need semicolon )
WHEN  Conditions 2 THEN  result 2 Or words 2( If it's a statement , Need semicolon )
...
ELSE  result n Or words n( If it's a statement , Need semicolon )
END [case]( If it's on begin end Need to add case, If you put it in select There is no need for )
  • give an example 1: Use CASE The... Of the process control statement 1 format , Judge val The value is equal to 1、 be equal to 2, Or both .
CASE val
    WHEN 1 THEN SELECT 'val is 1';
    WHEN 2 THEN SELECT 'val is 2';
    ELSE SELECT 'val is not 1 or 2';
END CASE;
  • give an example 2: Declaring stored procedures “update_salary_by_eid4”, Definition IN Parameters emp_id, Enter employee number . Judge the employee If the salary is lower than 9000 element , Just update the salary to 9000 element ; Salary is greater than or equal to 9000 Yuan and less than 10000 Of , But the bonus ratio by NULL Of , Just update the bonus ratio to 0.01; Other salary increases 100 element .
DELIMITER //
CREATE PROCEDURE update_salary_by_eid4(IN emp_id INT)
BEGIN
    DECLARE emp_sal DOUBLE;
    DECLARE bonus DECIMAL(3,2);
    SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id;
    SELECT commission_pct INTO bonus FROM employees WHERE employee_id = emp_id;
    CASE
    WHEN emp_sal<9000
    	THEN UPDATE employees SET salary=9000 WHERE employee_id = emp_id;
    WHEN emp_sal<10000 AND bonus IS NULL
    	THEN UPDATE employees SET commission_pct=0.01 WHERE employee_id = emp_id;
    ELSE
    	UPDATE employees SET salary=salary+100 WHERE employee_id = emp_id;
    END CASE;
END //
DELIMITER ;
  • give an example 3: Declaring stored procedures update_salary_by_eid5, Definition IN Parameters emp_id, Enter employee number . Judge the employee's Years of employment , If it is 0 year , Pay rise 50; If it is 1 year , Pay rise 100; If it is 2 year , Pay rise 200; If it is 3 year , Pay rise 300; If it is 4 year , Pay rise 400; Other salary increases 500.
DELIMITER //
CREATE PROCEDURE update_salary_by_eid5(IN emp_id INT)
BEGIN
    DECLARE emp_sal DOUBLE;
    DECLARE hire_year DOUBLE;
    SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id;
    SELECT ROUND(DATEDIFF(CURDATE(),hire_date)/365) INTO hire_year FROM employees
    WHERE employee_id = emp_id;
    CASE hire_year
        WHEN 0 THEN UPDATE employees SET salary=salary+50 WHERE employee_id = emp_id;
        WHEN 1 THEN UPDATE employees SET salary=salary+100 WHERE employee_id = emp_id;
        WHEN 2 THEN UPDATE employees SET salary=salary+200 WHERE employee_id = emp_id;
        WHEN 3 THEN UPDATE employees SET salary=salary+300 WHERE employee_id = emp_id;
        WHEN 4 THEN UPDATE employees SET salary=salary+400 WHERE employee_id = emp_id;
        ELSE UPDATE employees SET salary=salary+500 WHERE employee_id = emp_id;
    END CASE;
END //
DELIMITER ;

3) The cycle structure of LOOP

LOOP Loop statements are used to repeat certain statements .LOOP The statements in the loop are repeated until the loop is exited ( Use LEAVE Son sentence ), Jump out of the loop process .

LOOP The basic format of the statement is as follows :

[loop_label:] LOOP
 Statements executed in a loop 
END LOOP [loop_label]

among ,loop_label Express LOOP The annotation name of the statement , This parameter can be omitted .

give an example 1: Use LOOP Statement ,id Less than 10 The loop process is repeated .

DECLARE id INT DEFAULT 0;
add_loop:LOOP
    SET id = id +1;
    IF id >= 10 THEN LEAVE add_loop;
    END IF;
END LOOP add_loop;

give an example 2: When the market environment gets better , In order to reward everyone , Decided to give everyone a raise . Declaring stored procedures “update_salary_loop()”, Statement OUT Parameters num, Number of output cycles . Loop in the stored procedure to raise everyone's salary , The salary rose to The original 1.1 times . Until the average salary of the whole company reaches 12000 end . And count the number of cycles .

DELIMITER //
CREATE PROCEDURE update_salary_loop(OUT num INT)
BEGIN
	DECLARE avg_salary DOUBLE;
	DECLARE loop_count INT DEFAULT 0;
	SELECT AVG(salary) INTO avg_salary FROM employees;
	label_loop:LOOP
        IF avg_salary >= 12000 THEN LEAVE label_loop;
        END IF;
        UPDATE employees SET salary = salary * 1.1;
        SET loop_count = loop_count + 1;
        SELECT AVG(salary) INTO avg_salary FROM employees;
    END LOOP label_loop;
    SET num = loop_count;
END //
DELIMITER ;

4) The cycle structure of WHILE

WHILE Statement creates a loop with conditional judgment .WHILE When executing a statement , First judge the specified expression , Such as Fruit is true , Just execute the statements in the loop , Otherwise exit the loop .WHILE The basic format of the statement is as follows :

[while_label:] WHILE  The loop condition  DO
 The loop body 
END WHILE [while_label];

while_label by WHILE The annotation name of the statement ; If the result of the loop condition is true ,WHILE A statement or group of statements within a statement is executed , straight Until the cycle condition is false , Exit loop .

  • give an example 1:WHILE Statement example ,i Less than 10 when , The loop process... Will be repeated , The code is as follows :
DELIMITER //
CREATE PROCEDURE test_while()
BEGIN
    DECLARE i INT DEFAULT 0;
    WHILE i < 10 DO
    	SET i = i + 1;
    END WHILE;
    SELECT i;
END //
DELIMITER ;
# call 
CALL test_while();
  • give an example 2: When the market environment is bad , In order to tide over the difficulties , Decided to temporarily reduce everyone's salary . Declaring stored procedures “update_salary_while()”, Statement OUT Parameters num, Number of output cycles . Implement a loop in the stored procedure to reduce everyone's salary , Pay drop Original 90%. Until the average salary of the whole company reaches 5000 end . And count the number of cycles .
DELIMITER //
CREATE PROCEDURE update_salary_while(OUT num INT)
BEGIN
    DECLARE avg_sal DOUBLE ;
    DECLARE while_count INT DEFAULT 0;
    SELECT AVG(salary) INTO avg_sal FROM employees;
    WHILE avg_sal > 5000 DO
        UPDATE employees SET salary = salary * 0.9;
        SET while_count = while_count + 1;
        SELECT AVG(salary) INTO avg_sal FROM employees;
    END WHILE;
    SET num = while_count;
END //
DELIMITER ;

5) The cycle structure of REPEAT

REPEAT Statement creates a loop with conditional judgment . And WHILE The difference between cycles is ,REPEAT The loop first executes a loop , And then in UNTIL To judge the expression , If the conditions are met, exit , namely END REPEAT; If the conditions are not met , Then it will continue to execute the loop , Until the exit conditions are met .

REPEAT The basic format of the statement is as follows :

[repeat_label:] REPEAT
 The statement of the loop body 
UNTIL  Conditional expression to end the loop 
END REPEAT [repeat_label]

repeat_label by REPEAT The annotation name of the statement , This parameter can be omitted ;REPEAT A statement or group of statements within a statement is repeated , until expr_condition It's true .

give an example 1:

DELIMITER //
CREATE PROCEDURE test_repeat()
BEGIN
    DECLARE i INT DEFAULT 0;
    REPEAT
    	SET i = i + 1;
    UNTIL i >= 10
    END REPEAT;
    SELECT i;
END //
DELIMITER ;

give an example 2: When the market environment gets better , In order to reward everyone , Decided to give everyone a raise . Declaring stored procedures “update_salary_repeat()”, Statement OUT Parameters num, Number of output cycles . Loop in the stored procedure to raise everyone's salary , Pay rise Original 1.15 times . Until the average salary of the whole company reaches 13000 end . And count the number of cycles .

DELIMITER //
CREATE PROCEDURE update_salary_repeat(OUT num INT)
BEGIN
    DECLARE avg_sal DOUBLE ;
    DECLARE repeat_count INT DEFAULT 0;
    SELECT AVG(salary) INTO avg_sal FROM employees;
    REPEAT
    	UPDATE employees SET salary = salary * 1.15;
    	SET repeat_count = repeat_count + 1;
    	SELECT AVG(salary) INTO avg_sal FROM employees;
    UNTIL avg_sal >= 13000
    END REPEAT;
    SET num = repeat_count;
END //
DELIMITER ;

Comparison of three cycle structures :

  1. All three loops can omit the name , But if you add a loop control statement to the loop (LEAVE or ITERATE) You must add a name .

  2. LOOP: Generally used to implement simple " die " loop WHILE: Judge before you execute

  3. REPEAT: Execute before judge , Unconditionally execute at least once

6) Jump sentence of LEAVE sentence

LEAVE sentence : Can be used in loop statements , Or with BEGIN and END Wrapped program body , Means to jump out of a loop or out of Operation of program body . If you have experience with process oriented programming languages , You can take LEAVE Understood as a break.

The basic format is as follows :

LEAVE  Tagnames 

among ,label The parameter represents the flag of the loop .LEAVE and BEGIN … END Or loops are used together .

give an example 1: Create stored procedure “leave_begin()”, Statement INT Type of IN Parameters num. to BEGIN…END Tagging , And in BEGIN…END Use in IF Sentence judgment num The value of the parameter .

If num<=0, Then use LEAVE Statement exit BEGIN…END; If num=1, Then check “employees” The average salary of the table ; If num=2, Then check “employees” The minimum salary of the table ; If num>2, Then check “employees” The highest salary in the table .

IF Query at the end of the statement “employees” The total number of people in the table .

DELIMITER //
CREATE PROCEDURE leave_begin(IN num INT)
    begin_label: BEGIN
        IF num<=0
        	THEN LEAVE begin_label;
        ELSEIF num=1
        	THEN SELECT AVG(salary) FROM employees;
        ELSEIF num=2
        	THEN SELECT MIN(salary) FROM employees;
        ELSE
        	SELECT MAX(salary) FROM employees;
        END IF;
        SELECT COUNT(*) FROM employees;
    END //
DELIMITER ;

give an example 2: When the market environment is bad , In order to tide over the difficulties , Decided to temporarily reduce everyone's salary . Declaring stored procedures “leave_while()”, Statement OUT Parameters num, Number of output cycles , Used in stored procedures WHILE Cycle to reduce everyone's salary to the original salary 90%, Until the average salary of the whole company is less than or equal to 10000, And count the number of cycles .

DELIMITER //
CREATE PROCEDURE leave_while(OUT num INT)
BEGIN
    DECLARE avg_sal DOUBLE;# Record the average salary 
    DECLARE while_count INT DEFAULT 0; # Record the number of cycles 
    SELECT AVG(salary) INTO avg_sal FROM employees; #①  Initialization conditions 
    while_label:WHILE TRUE DO #②  The loop condition 
    #③  The loop body 
    IF avg_sal <= 10000 THEN
    LEAVE while_label;
    END IF;
    UPDATE employees SET salary = salary * 0.9;
    SET while_count = while_count + 1;
    #④  Iteration conditions 
    SELECT AVG(salary) INTO avg_sal FROM employees;
    END WHILE;
    # assignment 
    SET num = while_count;
END //
DELIMITER ;

7) Jump sentence of ITERATE sentence

ITERATE sentence : Can only be used in loop statements (LOOP、REPEAT and WHILE sentence ) Inside , Means to restart the cycle , Move the execution order to the beginning of the statement segment . If you have experience with process oriented programming languages , You can take ITERATE Understood as a continue, You mean for “ Cycle again ”.

The basic format of the statement is as follows :

ITERATE label

label The parameter represents the flag of the loop .ITERATE Statement must precede the loop flag .

give an example : Defining local variables num, The initial value is 0. Execute in a loop structure num + 1 operation .

  • If num < 10, Then continue to execute the loop ;
  • If num > 15, Then exit the loop structure ;
DELIMITER //
CREATE PROCEDURE test_iterate()
BEGIN
    DECLARE num INT DEFAULT 0;
    my_loop:LOOP
    	SET num = num + 1;
        IF num < 10
        	THEN ITERATE my_loop;
        ELSEIF num > 15
        	THEN LEAVE my_loop;
        END IF;
        SELECT 'MySQL';
    END LOOP my_loop;
END //
DELIMITER ;

4. The cursor

1) What is a cursor ( Or the cursor )

Although we can also pass the screening criteria WHERE and HAVING, Or a keyword that limits the return record LIMIT Return a record , however , But it can't be like a pointer in the result set , Position a record forward 、 Position a record backward , Or it can be located at random Bar record , And process the recorded data .

This is the time , You can use a cursor . The cursor , It provides a flexible operation mode , Enables us to locate each record in the result set , A data structure that operates on the data in the pointed record . Cursor let SQL This set oriented language has the ability of process oriented development .

stay SQL in , A cursor is a temporary database object , Can point to the data row pointer stored in the database table . Here's the cursor Acted as The function of the pointer , We can manipulate data rows by manipulating cursors .

MySQL Cursors can be used in stored procedures and functions .

2) Using cursor steps

The cursor must be declared before the handler is declared , And variables and conditions must also be declared before declaring cursors or handlers .

If we want to use cursors , It usually takes four steps . Different DBMS in , The syntax for using cursors may be slightly different .

First step , declare cursor

stay MySQL in , Use DECLARE Keyword to declare the cursor , The basic form of its grammar is as follows :

DECLARE cursor_name CURSOR FOR select_statement;

This grammar applies to MySQL,SQL Server,DB2 and MariaDB. If it is to use Oracle perhaps PostgreSQL, Need to be written :

DECLARE cursor_name CURSOR IS select_statement;

To use SELECT Statement to get the data result set , At this time, the traversal of the data has not started , here select_statement It stands for SELECT sentence , Returns a result set used to create the cursor .

such as :

DECLARE cur_emp CURSOR FOR
SELECT employee_id,salary FROM employees;

The second step , Open cursor

The syntax for opening a cursor is as follows :

OPEN cursor_name

When we define the cursor , If you want to use a cursor , The cursor must be opened first . When opening the cursor SELECT The query result set of the statement will be sent to the cursor workspace , For the following cursor Read one by one Prepare the records in the result set .

OPEN cur_emp;

The third step , Use cursors ( Get data from cursor )

The grammar is as follows :

FETCH cursor_name INTO var_name [, var_name] ...

The function of this sentence is to use cursor_name Use this cursor to read the current row , And save the data to var_name In this variable , The cursor pointer points to the next line . If the data row read by the cursor has multiple column names , It's in INTO Assign a value to multiple variable names after the keyword .

Be careful :var_name The cursor must be defined before it is declared .

FETCH cur_emp INTO emp_id, emp_sal ;

Be careful : The number of fields in the query result set of the cursor , Must follow INTO The following variables are the same , otherwise , When the stored procedure executes Hou ,MySQL It will give you an error .

Step four , Close cursor

CLOSE cursor_name

Yes OPEN There will be CLOSE, That is, open and close the cursor . When we finish using the cursor, we need to close the cursor . Because the cursor will Occupy system resources , If you don't close it in time , The cursor remains until the end of the stored procedure , Affect the efficiency of system operation . And close the cursor The operation of , The system resources occupied by the cursor will be released .

After closing the cursor , We can no longer retrieve the data rows in the query results , If you need to retrieve, you can only open the cursor again .

CLOSE cur_emp;

3) give an example

Create stored procedure “get_count_by_limit_total_salary()”, Statement IN Parameters limit_total_salary,DOUBLE type ; Statement OUT Parameters total_count,INT type . The function can accumulate the salary values of several employees with the highest salary , Until the total salary reaches limit_total_salary The value of the parameter , Return the accumulated number of people to total_count.

DELIMITER //
CREATE PROCEDURE get_count_by_limit_total_salary(IN limit_total_salary DOUBLE, OUT total_count INT)
BEGIN
	DECLARE sum_salary DOUBLE DEFAULT 0; #  Record the accumulated total salary 
	DECLARE cursor_salary DOUBLE DEFAULT 0; #  Record a salary value 
	DECLARE emp_count INT DEFAULT 0; #  Record the number of cycles 
	#  Define cursors 
	DECLARE emp_cursor CURSOR FOR SELECT salary FROM employees ORDER BY salary DESC;
	#  Open cursor 
	OPEN emp_cursor;
	
	REPEAT
		#  Use cursors ( Get data from cursor )
		FETCH emp_cursor INTO cursor_salary;
		SET sum_salary = sum_salary + cursor_salary;
		SET emp_count = emp_count + 1;
		UNTIL sum_salary >= limit_total_salary
	END REPEAT;
	set total_count = emp_count;
	#  Close cursor 
	CLOSE emp_cursor;
END //
DELIMITER;

4) Summary

The cursor is MySQL An important function of , by Read one by one The data in the result set , Provides the perfect solution . Compared with implementing the same function at the application level , Cursors can be used in stored programs , Efficient , The program is also more concise .

But it also brings some performance problems , For example, in the process of using cursors , Data rows will be Lock , In this way, there is a large amount of business concurrency When , It will not only affect the efficiency between businesses , Will Consume system resources , Cause insufficient memory , This is because cursors are processed in memory .

Suggest : Get into the habit of closing it after you use it , This can improve the overall efficiency of the system .

Add :MySQL 8.0 New features — Persistence of global variables

stay MySQL In the database , Global variables can be accessed through SET GLOBAL Statement . for example , Set the limit of server statement timeout , can To set the system variable max_execution_time To achieve :

SET GLOBAL MAX_EXECUTION_TIME=2000;

Use SET GLOBAL The variable value set by the statement will only Provisional entry into force . Database restart after , The server will start from MySQL Read in configuration file Default value of variable . MySQL 8.0 Version added SET PERSIST command . for example , Set the maximum number of connections to the server to 1000:

SET PERSIST global max_connections = 1000;

MySQL The configuration of the command will be saved in the data directory mysqld-auto.cnf In file , The file will be read the next time you start , Overwrite the default configuration file with its configuration .

The first 17 Chapter _ trigger

In actual development , We often encounter such situations : Yes 2 One or more interrelated tables , Such as Commodity information and Stock information branch Don't store in 2 In two different data tables , When we add a new product record , In order to ensure the integrity of the data , Must also Add an inventory record to the inventory table .

thus , We must write these two associated operation steps into the program , And use it Business Wrap it up , Make sure these two operations Be a Atomic manipulation , Or all , Or none at all . In case of special circumstances , You may also need to manually maintain the data , This is very It's easy to forget one step , Leading to data loss .

This is the time , We can use triggers . You can create a trigger , Let the insertion of commodity information data automatically trigger the insertion of inventory data . thus , Don't worry about missing data caused by forgetting to add inventory data .

1. Trigger Overview

The trigger is made by Events to trigger Some operation , These events include INSERT 、 UPDATE 、 DELETE event . The so-called event refers to the user's action or triggering a certain behavior . If the trigger program is defined , When the database executes these statements , It's equivalent to an event 了 , will Automatically The trigger performs the corresponding action .

When inserting data in the data table 、 Update and delete operations , When some database logic needs to be executed automatically , Triggers can be used to implement .

2. Trigger creation

1) grammar

CREATE TRIGGER  Trigger Name 
{BEFORE|AFTER} {INSERT|UPDATE|DELETE} ON  Table name 
FOR EACH ROW
 The block of statements executed by the trigger 

explain :

  • Table name : Represents the object monitored by the trigger .
  • BEFORE|AFTER : Indicates the trigger time .BEFORE Indicates that... Is triggered before the event ;AFTER Indicates that... Is triggered after the event .
  • INSERT|UPDATE|DELETE : Indicates the event triggered .
    • INSERT Indicates that... Is triggered when a record is inserted ;
    • UPDATE Indicates that... Is triggered when the record is updated ;
    • DELETE Indicates that... Is triggered when a record is deleted .
  • The block of statements executed by the trigger : It can be a single SQL sentence , It can also be done by BEGIN…END Structure .

2) The code for

give an example 1:

  1. Create data table :
CREATE TABLE test_trigger (
id INT PRIMARY KEY AUTO_INCREMENT,
t_note VARCHAR(30)
);

CREATE TABLE test_trigger_log (
id INT PRIMARY KEY AUTO_INCREMENT,
t_log VARCHAR(30)
);
  1. Create trigger : Create name as before_insert The trigger of , towards test_trigger Data table before inserting data , towards test_trigger_log Insert... Into the data table before_insert Log information .
DELIMITER //
CREATE TRIGGER before_insert
BEFORE INSERT ON test_trigger
FOR EACH ROW
BEGIN
    INSERT INTO test_trigger_log (t_log)
    VALUES('before_insert');
END //
DELIMITER ;
  1. towards test_trigger Insert data into the data table
INSERT INTO test_trigger (t_note) VALUES (' test  BEFORE INSERT  trigger ');
  1. see test_trigger_log Data in the data table
mysql> SELECT * FROM test_trigger_log;
+----+---------------+
| id | t_log |
+----+---------------+
| 1 | before_insert |
+----+---------------+
1 row in set (0.00 sec)

give an example 2:

Defining triggers “salary_check_trigger”, Based on employee table “employees” Of INSERT event , stay INSERT Check before Whether the salary of the new employee to be added is greater than that of his leader , If it is greater than the leader's salary , Then newspaper sqlstate_value by ’HY000’ The fault of By mistake , This makes the addition fail .

DELIMITER //
CREATE TRIGGER salary_check_trigger
BEFORE INSERT ON employees FOR EACH ROW
BEGIN
    DECLARE mgrsalary DOUBLE;
    SELECT salary INTO mgrsalary FROM employees WHERE employee_id = NEW.manager_id;
    IF NEW.salary > mgrsalary THEN
    	SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = ' The salary is higher than the leader's salary ';
    END IF;
END //
DELIMITER ;

In the above trigger declaration process NEW Keyword represents INSERT Add a new record of the statement .

3. see 、 Delete trigger

1) Check triggers

View trigger is to view the definition of triggers that already exist in the database 、 Status and syntax information .

The way 1: View the definitions of all triggers in the current database

SHOW TRIGGERS\G

The way 2: View the definition of a trigger in the current database

SHOW CREATE TRIGGER  Trigger Name 

The way 3: From the system library information_schema Of TRIGGERS Query in table “salary_check_trigger” Trigger information .

SELECT * FROM information_schema.TRIGGERS;

2) Delete trigger

Triggers are also database objects , Delete triggers also use DROP sentence , The syntax is as follows :

DROP TRIGGER IF EXISTS  Trigger Name ;

4. Advantages and disadvantages of flip flops

1) advantage

1、 Triggers ensure data integrity .

Suppose we use Purchase order header table (demo.importhead) To save the overall information of the purchase order , Include purchase order number 、 Vendor No 、 Warehouse number 、 Total incoming quantity 、 Total purchase amount and acceptance date .

listnumber ( Purchase order No )supplierid ( Purchaser number )stockid ( Reference library No )quantity ( Total quantity )importvalue ( Total amount )confirmationdate ( Acceptance date )

Use the purchase order details (demo.importdetails) To save the details of incoming goods , Include purchase order number 、 Product id 、 Purchase quantity The amount 、 Purchase price and purchase amount .

listnumber ( Purchase order No )itemnumber ( Product id )quantity ( Purchase quantity )importprice ( Purchase price )importvalue ( Purchase amount )

Whenever we enter 、 When deleting and modifying a purchase order detail data , The data in the purchase order details will change . This is the time , The total quantity and total amount in the purchase order header table must be recalculated , otherwise , The total quantity and total amount in the purchase order header table The amount is not equal to the total quantity and amount in the purchase order details , This is data inconsistency .

To solve this problem , We can use triggers , It is stipulated that whenever there is data insertion in the purchase order details 、 Modification and deletion when , Automatic triggering 2 Step by step :

1) Recalculate the total quantity and total amount in the purchase order details ;

2) Update the total quantity and total amount in the purchase order header table with the value calculated in step 1 .

thus , The value of total quantity and total amount in the purchase order header table , It is always the same as the total quantity calculated in the purchase order details The value of the total amount is the same , The data is consistent , There will be no contradiction .

2、 Triggers can help us log operations .

Using triggers , You can record exactly when and what happened . such as , Record the trigger for modifying the member's stored value , This is a good example . This is for the specific scenario when we perform the restore operation , It's helpful to better locate the cause of the problem .

3、 Triggers can also be used before manipulating data , Check the validity of the data .

such as , When the supermarket buys goods , The warehouse keeper needs to enter the purchase price . however , Human operation is easy to make mistakes , For example, when entering quantity , Scan the bar code in ; When entering the amount , Look at the string , The entered price far exceeds the selling price , Resulting in huge losses on the book …… These can be triggered , Before the actual insert or update operation , Check the corresponding data , Prompt errors in time , Prevent erroneous data from entering the system .

2) shortcoming

1、 One of the biggest problems with triggers is poor readability .

Because triggers are stored in the database , And driven by events , This means that triggers may not be controlled by the application layer . This is very challenging for system maintenance .

2、 Change of relevant data , May cause trigger errors .

Especially the change of data table structure , Can cause trigger errors , Thus affecting the normal operation of data operation . These are due to the concealment of the trigger itself , It affects the efficiency of error cause troubleshooting in the application .

3) Be careful

Be careful , If a foreign key constraint is defined in the child table , And the foreign key specifies ON UPDATE/DELETE CASCADE/SET NULL Clause , At this time, when modifying the key value referenced by the parent table or deleting the record row referenced by the parent table , It will also cause modification and deletion of sub tables , At this point, based on the sub table UPDATE and DELETE The trigger defined by the statement is not activated .

for example : Employee table based on sub table (t_employee) Of DELETE Statement defines the trigger t1, And the department number of the sub table (did) The field defines the foreign key constraint and references the parent table department table (t_department) The primary key column of the department number (did), And the foreign key is added “ON DELETE SET NULL” Clause , Then, if the parent table department table is deleted at this time (t_department) In the sub table employee table (t_employee) When there are department records matching records , Will cause sub table employee table (t_employee) The department number of the matching record (did) It is amended as follows NULL, mysql> update demo.membermaster set memberdeposit=20 where memberid = 2; ERROR 1054 (42S22): Unknown column ‘aa’ in ‘field list’ However, the trigger is not activated at this time t1. Only direct sub table employee table (t_employee) perform DELETE Statement to activate the trigger t1.

The first 18 Chapter _MySQL8 Other new features

1. MySQL8 Overview of new features

MySQL from 5.7 The version was released directly 8.0 edition , It can be seen that this is an exciting milestone version .MySQL 8 The version has made significant improvements and enhancements in function , Developer pair MySQL The source code is reconstructed , The most prominent point is more MySQL Optimizer The optimizer has been improved . Not only has it improved in speed , It also brings users better performance and better experience .

1) MySQL8.0 New features

  1. Easier NoSQL Support NoSQL Generally refers to non relational database and data storage . With the rapid development of Internet platform , Tradition The relational database of has been increasingly unable to meet the demand . from 5.6 Version start ,MySQL Start supporting simple NoSQL Storage function . MySQL 8 This function has been optimized , Achieve... In a more flexible way NoSQL function , No longer rely on patterns (schema).

  2. Better index In the query , Using index correctly can improve the efficiency of query .MySQL 8 Added in Hide index and Descending order lead . Hidden indexes can be used to test the impact of removing indexes on query performance . When multiple column indexes are mixed in the query , Use descending index Can improve query performance .

  3. More perfect JSON Support MySQL from 5.7 Start supporting native JSON Data storage ,MySQL 8 This function has been optimized , increase Aggregate function JSON_ARRAYAGG() and JSON_OBJECTAGG() , Aggregate parameters into JSON Array or object , Added inline The operator ->>, Is the column path operator -> The enhancement of , Yes JSON The ranking has been improved , And optimized JSON Update operation for .

  4. Security and account management MySQL 8 Added in caching_sha2_password Licensing plug-ins 、 role 、 Password history and FIPS Mode support , These features improve the security and performance of the database , Make the database administrator more flexible in account management .

  5. InnoDB The change of InnoDB yes MySQL The default storage engine , Is the preferred engine for transactional databases , Support transaction security (ACID), Support row locking and foreign keys . stay MySQL 8 In the version ,InnoDB Increasing 、 Indexes 、 encryption 、 Deadlock 、 Sharing locks, etc Did a lot of Improve and optimize , And support atomic data definition language (DDL), Improved data security , Provide better... For transactions Support .

  6. The data dictionary Prior to MySQL In the version , Dictionary data is stored in metadata files and non transaction tables . from MySQL 8 Start adding Transaction data dictionary , Database object information is stored in this dictionary , These data dictionaries are stored in internal transaction tables .

  7. Atomic data definition statement MySQL 8 Start supporting atomic data definition statements (Automic DDL), namely atom DDL . at present , Only InnoDB The storage engine supports atomic DDL. Atomic data definition statement (DDL) Will work with DDL Operation related data dictionary update 、 Storage engine operation 、 Binary log writes are combined into a single atomic transaction , This makes even if the server crashes , Transactions are also committed or rolled back . Tables created using a storage engine that supports atomic operations , In execution DROP TABLE、CREATE TABLE、ALTER TABLE、 RENAME TABLE、TRUNCATE TABLE、CREATE TABLESPACE、DROP TABLESPACE When waiting for operation , All support atomic operation do , That is, the transaction is either fully successful , Or roll back after failure , No more partial submissions . From MySQL 5.7 Copied to the MySQL 8 Statements in version , You can add IF EXISTS or IF NOT EXISTS Statement to avoid errors .

  8. Resource management MySQL 8 Start supporting the creation and management of resource groups , Allows threads running in the server to be assigned to specific groups , In order to Threads execute based on the resources available in the group . Group properties can control the resources in the group , Enable or limit resource consumption within the group . Database administrators can Change these properties appropriately for different workloads . at present ,CPU Time is a controllable resource , from “ fictitious CPU” This concept is used to show in , The term contains CPU The number of core , hyper-threading , Hardware threads and so on . The server determines which virtual machines are available at startup CPU Number . Have The database administrator with corresponding permissions can transfer these CPU Associated with a resource group , And assign threads to the resource group . The resource group component is MySQL Resource group management in provides SQL Interface . The properties of the resource group are used to define the resource group .MySQL There are two default groups in , System groups and users Group , The default group cannot be deleted , Its properties cannot be changed . For user-defined groups , When a resource group is created, all attribute , Remove names and types , Other properties can be changed after creation . On some platforms , Or some MySQL The match of Set time , The function of resource management will be limited , Not even available . for example , If the thread pool plug-in is installed , Or use macOS System , Resource management will be unavailable . stay FreeBSD and Solaris In the system , Resource thread priority will be invalidated . stay Linux System in , Only configuration CAP_SYS_NICE attribute , Resource management priorities work .

  9. Character set support MySQL 8 The default character set in consists of latin1 Change to utf8mb4 , And for the first time, it adds a set specifically used in Japanese close ,utf8mb4_ja_0900_as_cs.

  10. Optimizer enhancement MySQL The optimizer began to support hidden and descending indexes . Hidden indexes are not used by the optimizer , Verify the necessity of the index You do not need to delete the index when you want sex , Hide the index first , If the optimizer has no performance impact, you can actually delete the index . Descending index allows The optimizer sorts multiple columns , And allow inconsistent sorting order .

  11. Common table expression Common table expression (Common Table Expressions) Referred to as CTE,MySQL Recursion and non recursion are now supported In two forms CTE.CTE By means of SELECT Statement or other specific statements Use WITH Statement on the temporary result set Name it .

    The basic grammar is as follows :

    WITH cte_name (col_name1,col_name2 ...) AS (Subquery)
    SELECT * FROM cte_name;
    
    

​ Subquery Represents a subquery , Use... Before subquery WITH Statement names the result set cte_name, You can use... In subsequent queries cte_name The query .

  1. Window function MySQL 8 Start supporting window functions . Most existing in previous versions Aggregate functions stay MySQL 8 You can also do so. Use as a window function .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-GFKI3Tr0-1655907404981)(MySQL The basic chapter .assets/image-20220613202507072.png)]

  1. Regular expression support MySQL stay 8.0.4 Later versions will support Unicode The international component library implements regular expression operation , This way can not only provide complete Unicode Support , And it's multi byte security coding .MySQL Added REGEXP_LIKE()、 EGEXP_INSTR()、REGEXP_REPLACE() and REGEXP_SUBSTR() And other functions to improve performance . in addition ,regexp_stack_limit and regexp_time_limit System variables can control resource consumption through the matching engine .
  2. Internal temporary watch TempTable The storage engine replaces MEMORY The storage engine becomes the default storage engine for internal temporary tables .TempTable Storage The engine is VARCHAR and VARBINARY Columns provide efficient storage .internal_tmp_mem_storage_engine The session variable defines the internal Storage engine for temporary tables , There are two optional values ,TempTable and MEMORY, among TempTable Is the default storage engine . temptable_max_ram The system configuration item defines TempTable The maximum amount of memory that the storage engine can use .
  3. logging stay MySQL 8 The error log subsystem in consists of a series of MySQL Components . These components are made up of system variables log_error_services To configure the , It can filter and write log events . WITH cte_name (col_name1,col_name2 …) AS (Subquery) SELECT * FROM cte_name;
  4. Backup the lock The new backup lock allows data manipulation statements to be executed during online backup , At the same time, prevent operations that may cause inconsistent snapshots . new The backup lock is controlled by LOCK INSTANCE FOR BACKUP and UNLOCK INSTANCE Syntax support , Performing these operations requires backup management Member privileges .
  5. Enhanced MySQL Copy MySQL 8 Replication support for JSON file Partially updated Binary logging , This record Use compact Binary format , So as to save complete records JSON Document space . When using statement based logging , This compact diary The recording will be completed automatically , And by putting new binlog_row_value_options The system variable value is set to PARTIAL_JSON To enable .

2) MySQL8.0 Remove old features

stay MySQL 5.7 If the application developed on version uses MySQL8.0 Removed features , The statement may fail , Or make a difference The results of the implementation of . To avoid these problems , For applications that use the remove feature , Every effort should be made to correct and avoid the use of these features , And do Alternative methods may be used .

  1. The query cache The query cache has been removed , The deleted items are : (1) sentence :FLUSH QUERY CACHE and RESET QUERY CACHE. (2) System variables :query_cache_limit、query_cache_min_res_unit、query_cache_size、 query_cache_type、query_cache_wlock_invalidate. (3) State variables :Qcache_free_blocks、 Qcache_free_memory、Qcache_hits、Qcache_inserts、Qcache_lowmem_prunes、Qcache_not_cached、 Qcache_queries_in_cache、Qcache_total_blocks. (4) Thread state :checking privileges on cached query、checking query cache for query、invalidating query cache entries、sending cached result to client、storing result in query cache、waiting for query cache lock.
  2. Encryption related The encryption related contents deleted are :ENCODE()、DECODE()、ENCRYPT()、DES_ENCRYPT() and DES_DECRYPT() function , Configuration item des-key-file, System variables have_crypt,FLUSH Of the statement DES_KEY_FILE Options , HAVE_CRYPT CMake Options . For removed ENCRYPT() function , Consider using SHA2() replace , For other removed functions , send use AES_ENCRYPT() and AES_DECRYPT() replace .
  3. Spatial function correlation stay MySQL 5.7 In the version , The space is marked obsolete by more than one function . These outdated functions are MySQL 8 Have been remove , Only the corresponding ST_ and MBR function .
  4. \N and NULL stay SQL In the sentence , The parser will no longer \N As NULL, So in SQL Statement should use NULL Instead of \N. This change It will not affect the use of LOAD DATA INFILE perhaps SELECT…INTO OUTFILE Import and export operation files . In such operations ,NULL Still equivalent to \N.
  5. mysql_install_db stay MySQL In distribution , Removed mysql_install_db Program , The initialization of data dictionary needs to be called with -- initialize perhaps –initialize-insecure Option mysqld Instead of realizing . in addition ,–bootstrap and INSTALL_SCRIPTDIR CMake Has also been deleted .
  6. General partition handler The universal partition handler has been removed from MySQL Removed from service . In order to achieve a given table partition , The storage used by the table The storage engine needs its own partition handler . Provide local partition support MySQL The storage engine has two , namely InnoDB and NDB, And in the MySQL 8 China only supports InnoDB.
  7. System and state variable information stay INFORMATION_SCHEMA In the database , The system and state variable information is no longer maintained . GLOBAL_VARIABLES、SESSION_VARIABLES、GLOBAL_STATUS、SESSION_STATUS All tables have been deleted . in addition , system System variable show_compatibility_56 Has also been deleted . The deleted state variables are Slave_heartbeat_period、 Slave_last_heartbeat,Slave_received_heartbeats、Slave_retried_transactions、Slave_running. The above has been deleted Can be replaced by the corresponding content in the performance mode .
  8. mysql_plugin Tools mysql_plugin Tools are used to configure MySQL Server plug-ins , Has now been deleted , You can use –plugin-load or - -plugin-load-add Option loads the plug-in when the server starts or is used at run time INSTALL PLUGIN Statement to load a plug-in to replace the Tools .

2. New characteristics 1: Window function

1) Use the window function to compare before and after

Suppose I have such a data table now , It shows the sales of a shopping website in each city and each district :

CREATE TABLE sales(
id INT PRIMARY KEY AUTO_INCREMENT,
city VARCHAR(15),
county VARCHAR(15),
sales_value DECIMAL
);
INSERT INTO sales(city,county,sales_value)
VALUES
(' Beijing ',' haidian ',10.00),
(' Beijing ',' The rising sun ',20.00),
(' Shanghai ',' Whampoa ',30.00),
(' Shanghai ',' Changning ',10.00);

Inquire about :

mysql> SELECT * FROM sales;
+----+------+--------+-------------+
| id | city | county | sales_value |
+----+------+--------+-------------+
| 1  |  Beijing   |   haidian    |      10    |
| 2  |  Beijing   |   The rising sun    |      20    |
| 3  |  Shanghai   |   Whampoa    |      30    |
| 4  |  Shanghai   |   Changning    |      10    |
+----+------+--------+-------------+
4 rows in set (0.00 sec)

demand : Now calculate the total sales of this website in each city 、 Total sales across the country 、 The ratio of sales in each district to sales in the city , And as a percentage of total sales .

If you use grouping and aggregation functions , It takes several steps to calculate .

First step , Calculate the total sales amount , And save it in the temporary form a:

CREATE TEMPORARY TABLE a --  Create a temporary table 
SELECT SUM(sales_value) AS sales_value --  Calculate the total amount 
FROM sales;

Check the temporary table a :

mysql> SELECT * FROM a;
+-------------+
| sales_value |
+-------------+
| 70 |
+-------------+
1 row in set (0.00 sec)

The second step , Calculate the total sales of each city and store it in the temporary table b:

CREATE TEMPORARY TABLE b --  Create a temporary table 
SELECT city, SUM(sales_value) AS sales_value --  Calculate the total city sales 
FROM sales
GROUP BY city;

View temporary table b :

mysql> SELECT * FROM b;
+------+-------------+
| city | sales_value |
+------+-------------+
|  Beijing   |     30      |
|  Shanghai   |     40      |
+------+-------------+
2 rows in set (0.00 sec)

The third step , Calculate the proportion of sales in each district to the total amount of the city , And proportion in total sales amount . We can get the required results through the following connection query :

mysql> SELECT s.city AS  City ,s.county AS  District ,s.sales_value AS  District Sales ,
-> b.sales_value AS  City Sales ,s.sales_value/b.sales_value AS  Market to market ratio ,
-> a.sales_value AS  Total sales ,s.sales_value/a.sales_value AS  Total ratio 
-> FROM sales s
-> JOIN b ON (s.city=b.city) --  Connect the provisional statistical results of the city 
-> JOIN a --  Connect the provisional table of total amount 
-> ORDER BY s.city,s.county;
+------+------+----------+----------+--------+----------+--------+
|  City  |  District  |  District Sales  |  City Sales  |  Market to market ratio  |  Total sales  |  Total ratio  |
+------+------+----------+----------+--------+----------+--------+
|  Shanghai  |  Changning  | 10 | 40 | 0.2500 | 70 | 0.1429 |
|  Shanghai  |  Whampoa  | 30 | 40 | 0.7500 | 70 | 0.4286 |
|  Beijing  |  The rising sun  | 20 | 30 | 0.6667 | 70 | 0.2857 |
|  Beijing  |  haidian  | 10 | 30 | 0.3333 | 70 | 0.1429 |
+------+------+----------+----------+--------+----------+--------+
4 rows in set (0.00 sec)

Results show : City sales amount 、 Proportion of market sales 、 Total sales amount 、 The proportion of total sales has been calculated .

Same query , If you use the window function , It's much simpler . We can use the following code to implement :

mysql> SELECT city AS  City ,county AS  District ,sales_value AS  District Sales ,
-> SUM(sales_value) OVER(PARTITION BY city) AS  City Sales , --  Calculate City Sales 
-> sales_value/SUM(sales_value) OVER(PARTITION BY city) AS  Market to market ratio ,
-> SUM(sales_value) OVER() AS  Total sales , --  Calculate total sales 
-> sales_value/SUM(sales_value) OVER() AS  Total ratio 
-> FROM sales
-> ORDER BY city,county;
+------+------+----------+----------+--------+----------+--------+
|  City  |  District  |  District Sales  |  City Sales  |  Market to market ratio  |  Total sales  |  Total ratio  |
+------+------+----------+----------+--------+----------+--------+
|  Shanghai  |  Changning  | 10 | 40 | 0.2500 | 70 | 0.1429 |
|  Shanghai  |  Whampoa  | 30 | 40 | 0.7500 | 70 | 0.4286 |
|  Beijing  |  The rising sun  | 20 | 30 | 0.6667 | 70 | 0.2857 |
|  Beijing  |  haidian  | 10 | 30 | 0.3333 | 70 | 0.1429 |
+------+------+----------+-----------+--------+----------+--------+
4 rows in set (0.00 sec)

Results show , We got the same result as the query above .

Use window functions , It takes only one step to complete the query . and , Since no temporary table is used , The efficiency of execution is also higher . Very obvious however , In this scenario, the results of grouping statistics are used to calculate each record , Using window functions is better .

2) Window function classification

MySQL from 8.0 The version began to support window functions . The window function is similar to grouping data in a query , The difference is , Grouping operation will aggregate the results of grouping into a record , The window function is to put the result in each data record .

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 .

MySQL The URL of the official website window function is https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptio ns.html#function_row-number.

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 :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-asridlDc-1655907404981)(MySQL The basic chapter .assets/image-20220613210116486.png)]

3) Grammatical structure

The syntax structure of window function is :

 function  OVER([PARTITION BY  Field name  ORDER BY  Field name  ASC|DESC])

Or is it :

 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 .

4) Classified explanation

Create table :

CREATE TABLE goods(
id INT PRIMARY KEY AUTO_INCREMENT,
category_id INT,
category VARCHAR(15),
NAME VARCHAR(30),
price DECIMAL(10,2),
stock INT,
upper_time DATETIME
);

Add data :

INSERT INTO goods(category_id,category,NAME,price,stock,upper_time)
VALUES
(1, ' Women's wear / Women's Boutique ', 'T T-shirt ', 39.90, 1000, '2020-11-10 00:00:00'),
(1, ' Women's wear / Women's Boutique ', ' dress ', 79.90, 2500, '2020-11-10 00:00:00'),
(1, ' Women's wear / Women's Boutique ', ' fleece ', 89.90, 1500, '2020-11-10 00:00:00'),
(1, ' Women's wear / Women's Boutique ', ' A pair of jeans ', 89.90, 3500, '2020-11-10 00:00:00'),
(1, ' Women's wear / Women's Boutique ', ' Pleated skirt ', 29.90, 500, '2020-11-10 00:00:00'),
(1, ' Women's wear / Women's Boutique ', ' Woolen coat ', 399.90, 1200, '2020-11-10 00:00:00'),
(2, ' Outdoor sports ', ' Bicycle ', 399.90, 1000, '2020-11-10 00:00:00'),
(2, ' Outdoor sports ', ' Mountain Bike ', 1399.90, 2500, '2020-11-10 00:00:00'),
(2, ' Outdoor sports ', ' Alpenstocks ', 59.90, 1500, '2020-11-10 00:00:00'),
(2, ' Outdoor sports ', ' Riding equipment ', 399.90, 3500, '2020-11-10 00:00:00'),
(2, ' Outdoor sports ', ' Sport coat ', 799.90, 500, '2020-11-10 00:00:00'),
(2, ' Outdoor sports ', ' Skate ', 499.90, 1200, '2020-11-10 00:00:00');

The following for goods Table to verify the function of each window function .

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 information of each commodity in descending order under each commodity category in the data table .

mysql> SELECT ROW_NUMBER() OVER(PARTITION BY category_id ORDER BY price DESC) AS
row_num, id, category_id, category, NAME, price, stock
FROM goods;
+---------+----+-------------+---------------+------------+---------+-------+
| row_num | id | category_id |    category   |     NAME   |  price  | stock |
+---------+----+-------------+---------------+------------+---------+-------+
|    1    |  6 |     1       |   Women's wear / Women's Boutique   |  Woolen coat      | 399.90  | 1200  |
|    2    |  3 |     1       |   Women's wear / Women's Boutique   |  fleece         | 89.90   | 1500  |
|    3    |  4 |     1       |   Women's wear / Women's Boutique   |  A pair of jeans        | 89.90   | 3500  |
|    4    |  2 |     1       |   Women's wear / Women's Boutique   |  dress        | 79.90   | 2500  |
|    5    |  1 |     1       |   Women's wear / Women's Boutique   | T T-shirt          | 39.90   | 1000  |
|    6    |  5 |     1       |   Women's wear / Women's Boutique   |  Pleated skirt        | 29.90   | 500   |
|    1    |  8 |     2       |      Outdoor sports    |  Mountain Bike     | 1399.90 | 2500  |
|    2    | 11 |     2       |      Outdoor sports    |  Sport coat       | 799.90  | 500  |
|    3    | 12 |     2       |      Outdoor sports    |  Skate          | 499.90  | 1200  |
|    4    |  7 |     2       |      Outdoor sports    |  Bicycle        | 399.90  | 1000  |
|    5    | 10 |     2       |      Outdoor sports    |  Riding equipment      | 399.90  | 3500  |
|    6    |  9 |     2       |      Outdoor sports    |  Alpenstocks        | 59.90   | 1500  |
+---------+----+-------------+---------------+------------+---------+-------+
12 rows in set (0.00 sec)

give an example : Inquire about goods The highest price under each commodity category in the data sheet 3 Product information .

mysql> 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;
+---------+----+-------------+---------------+------------+---------+-------+
| row_num | id | category_id |     category  |      NAME  |  price  | stock |
+---------+----+-------------+---------------+------------+---------+-------+
|     1   |  6 |      1      |  Women's wear / Women's Boutique    |  Woolen coat      | 399.90  | 1200  |
|     2   |  3 |      1      |  Women's wear / Women's Boutique    |  fleece         | 89.90   | 1500  |
|     3   |  4 |      1      |  Women's wear / Women's Boutique    |  A pair of jeans       | 89.90    | 3500 |
|     1   |  8 |      2      |  Outdoor sports        |  Mountain Bike    | 1399.90  | 2500 |
|     2   | 11 |      2      |  Outdoor sports        |  Sport coat      | 799.90  | 500   |
|     3   | 12 |      2      |  Outdoor sports        |  Skate         | 499.90   | 1200 |
+---------+----+-------------+---------------+------------+----------+-------+
6 rows in set (0.00 sec)

In the name of “ Women's wear / Women's Boutique ” In the commodity category of , The price of two products is 89.90 element , They are sweaters and jeans . Two items The serial numbers of should all be 2, Not one for 2, For another 3. here , have access to RANK() Functions and DENSE_RANK() Function solution " .

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.

give an example : Use RANK() Function to obtain goods The price of each category in the data table is sorted from high to low .

mysql> SELECT RANK() OVER(PARTITION BY category_id ORDER BY price DESC) AS row_num,
-> id, category_id, category, NAME, price, stock
-> FROM goods;
+---------+----+-------------+---------------+------------+---------+-------+
| row_num | id | category_id | category      | NAME       | price   | stock |
+---------+----+-------------+---------------+------------+---------+-------+
|     1   | 6  |     1       |  Women's wear / Women's Boutique    |  Woolen coat      | 399.90  | 1200  |
|     2   | 3  |     1       |  Women's wear / Women's Boutique    |  fleece         | 89.90   | 1500  |
|     2   | 4  |     1       |  Women's wear / Women's Boutique    |  A pair of jeans       | 89.90   | 3500   |
|     4   | 2  |     1       |  Women's wear / Women's Boutique    |  dress       | 79.90   | 2500   |
|     5   | 1  |     1       |  Women's wear / Women's Boutique    | T T-shirt         | 39.90   | 1000   |
|     6   | 5  |     1       |  Women's wear / Women's Boutique    |  Pleated skirt       | 29.90   | 500    |
|     1   | 8  |     2       |  Outdoor sports        |  Mountain Bike    | 1399.90 | 2500   |
|     2   | 11 |     2       |  Outdoor sports        |  Sport coat      | 799.90  | 500   |
|     3   | 12 |     2       |  Outdoor sports        |  Skate         | 499.90  | 1200   |
|     4   | 7  |     2       |  Outdoor sports        |  Bicycle       | 399.90   | 1000  |
|     4   | 10 |     2       |  Outdoor sports        |  Riding equipment     | 399.90   | 3500  |
|     6   | 9  |     2       |  Outdoor sports        |  Alpenstocks       | 59.90   | 1500   |
+---------+----+-------------+---------------+------------+---------+-------+
12 rows in set (0.00 sec)

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. give an example : Use DENSE_RANK() Function to obtain goods The price of each category in the data table is sorted from high to low .

mysql> SELECT DENSE_RANK() OVER(PARTITION BY category_id ORDER BY price DESC) AS
row_num,
-> id, category_id, category, NAME, price, stock
-> FROM goods;
+---------+----+-------------+---------------+------------+---------+-------+
| row_num | id | category_id | category      | NAME       | price   | stock |
+---------+----+-------------+---------------+------------+---------+-------+
|    1    | 6  |      1      |  Women's wear / Women's Boutique    |      Woolen coat  | 399.90 | 1200   |
|    2    | 3  |      1      |  Women's wear / Women's Boutique    |      fleece     | 89.90  | 1500   |
|    2    | 4  |      1      |  Women's wear / Women's Boutique    |      A pair of jeans   | 89.90   | 3500  |
|    3    | 2  |      1      |  Women's wear / Women's Boutique    |      dress   | 79.90   | 2500  |
|    4    | 1  |      1      |  Women's wear / Women's Boutique    |     T T-shirt     | 39.90   | 1000  |
|    5    | 5  |      1      |  Women's wear / Women's Boutique    |      Pleated skirt   | 29.90   | 500   |
|    1    | 8  |      2      |  Outdoor sports        |     Mountain Bike | 1399.90 | 2500 |
|    2    | 11 |      2      |  Outdoor sports        |     Sport coat   | 799.90 | 500    |
|    3    | 12 |      2      |  Outdoor sports        |     Skate      | 499.90 | 1200   |
|    4    | 7  |      2      |  Outdoor sports        |     Bicycle     | 399.90 | 1000   |
|    4    | 10 |      2      |  Outdoor sports        |     Riding equipment   | 399.90 | 3500   |
|    5    | 9  |      2      |  Outdoor sports        |     Alpenstocks     | 59.90 | 1500   |
+---------+----+-------------+---------------+------------+---------+-------+
12 rows in set (0.00 sec)

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)

among ,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 .

give an example : Calculation goods The name in the data table is “ Women's wear / Women's Boutique ” Of goods under the category of PERCENT_RANK value .

# Writing a :
SELECT RANK() OVER (PARTITION BY category_id ORDER BY price DESC) AS r,
PERCENT_RANK() OVER (PARTITION BY category_id ORDER BY price DESC) AS pr,
id, category_id, category, NAME, price, stock
FROM goods
WHERE category_id = 1;
# Write two :
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 .

give an example : Inquire about goods The proportion in the data sheet that is less than or equal to the current price .

mysql> SELECT CUME_DIST() OVER(PARTITION BY category_id ORDER BY price ASC) AS cd,
-> id, category, NAME, price
-> FROM goods;
+---------------------+----+---------------+------------+---------+
|                cd   | id | category      | NAME       | price   |
+---------------------+----+---------------+------------+---------+
| 0.16666666666666666 | 5  |  Women's wear / Women's Boutique    |  Pleated skirt       | 29.90 |
| 0.3333333333333333  | 1  |  Women's wear / Women's Boutique    | T T-shirt         | 39.90 |
| 0.5                 | 2  |  Women's wear / Women's Boutique    |  dress       | 79.90 |
| 0.8333333333333334  | 3  |  Women's wear / Women's Boutique    |  fleece        | 89.90 |
| 0.8333333333333334  | 4  |  Women's wear / Women's Boutique    |  A pair of jeans      | 89.90 |
| 1                   | 6  |  Women's wear / Women's Boutique    |  Woolen coat     | 399.90 |
| 0.16666666666666666 | 9  |  Outdoor sports        |  Alpenstocks       | 59.90 |
| 0.5                 | 7  |  Outdoor sports        |  Bicycle       | 399.90 |
| 0.5                 | 10 |  Outdoor sports        |  Riding equipment      | 399.90 |
| 0.6666666666666666  | 12 |  Outdoor sports        |  Skate         | 499.90 |
| 0.8333333333333334  | 11 |  Outdoor sports        |  Sport coat      | 799.90 |
| 1                   | 8  |  Outdoor sports        |  Mountain Bike    | 1399.90 |
+---------------------+----+---------------+------------+---------+
12 rows in set (0.00 sec)

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 .

give an example : Inquire about goods The difference between the previous commodity price and the current commodity price in the data table .

mysql> SELECT id, category, NAME, price, pre_price, price - pre_price AS diff_price
-> FROM (
-> SELECT id, category, NAME, price,LAG(price,1) OVER w AS pre_price
-> FROM goods
-> WINDOW w AS (PARTITION BY category_id ORDER BY price)) t;
+----+---------------+------------+---------+-----------+------------+
| id | category | NAME | price | pre_price | diff_price |
+----+---------------+------------+---------+-----------+------------+
| 5 |  Women's wear / Women's Boutique  |  Pleated skirt  | 29.90 | NULL | NULL |
| 1 |  Women's wear / Women's Boutique  | T T-shirt  | 39.90 | 29.90 | 10.00 |
| 2 |  Women's wear / Women's Boutique  |  dress  | 79.90 | 39.90 | 40.00 |
| 3 |  Women's wear / Women's Boutique  |  fleece  | 89.90 | 79.90 | 10.00 |
| 4 |  Women's wear / Women's Boutique  |  A pair of jeans  | 89.90 | 89.90 | 0.00 |
| 6 |  Women's wear / Women's Boutique  |  Woolen coat  | 399.90 | 89.90 | 310.00 |
| 9 |  Outdoor sports  |  Alpenstocks  | 59.90 | NULL | NULL |
| 7 |  Outdoor sports  |  Bicycle  | 399.90 | 59.90 | 340.00 |
| 10 |  Outdoor sports  |  Riding equipment  | 399.90 | 399.90 | 0.00 |
| 12 |  Outdoor sports  |  Skate  | 499.90 | 399.90 | 100.00 |
| 11 |  Outdoor sports  |  Sport coat  | 799.90 | 499.90 | 300.00 |
| 8 |  Outdoor sports  |  Mountain Bike  | 1399.90 | 799.90 | 600.00 |
+----+---------------+------------+---------+-----------+------------+
12 rows in set (0.00 sec)

2.LEAD(expr,n) function

LEAD(expr,n) The function returns the last... Of the current line n Yes expr Value .

give an example : Inquire about goods The difference between the price of the last commodity in the data table and the current commodity price .

mysql> SELECT id, category, NAME, behind_price, price,behind_price - price AS
diff_price
-> FROM(
-> SELECT id, category, NAME, price,LEAD(price, 1) OVER w AS behind_price
-> FROM goods WINDOW w AS (PARTITION BY category_id ORDER BY price)) t;
+----+---------------+------------+--------------+---------+------------+
| id | category      | NAME       | behind_price | price   | diff_price |
+----+---------------+------------+--------------+---------+------------+
| 5  |  Women's wear / Women's Boutique    |  Pleated skirt        | 39.90       | 29.90 | 10.00 |
| 1  |  Women's wear / Women's Boutique    | T T-shirt          | 79.90       | 39.90 | 40.00 |
| 2  |  Women's wear / Women's Boutique    |  dress       | 89.90        | 79.90 | 10.00 |
| 3  |  Women's wear / Women's Boutique    |  fleece         | 89.90       | 89.90 | 0.00 |
| 4  |  Women's wear / Women's Boutique    |  A pair of jeans        | 399.90     | 89.90 | 310.00 |
| 6  |  Women's wear / Women's Boutique    |  Woolen coat      | NULL       | 399.90 | NULL |
| 9  |  Outdoor sports        |  Alpenstocks        | 399.90    | 59.90 | 340.00 |
| 7  |  Outdoor sports        |  Bicycle        | 399.90    | 399.90 | 0.00 |
| 10 |  Outdoor sports        |  Riding equipment      | 499.90     | 399.90 | 100.00 |
| 12 |  Outdoor sports        |  Skate          | 799.90    | 499.90 | 300.00 |
| 11 |  Outdoor sports        |  Sport coat      | 1399.90    | 799.90 | 600.00 |
| 8  |  Outdoor sports        |  Mountain Bike    | NULL       | 1399.90 | NULL |
+----+---------------+------------+--------------+---------+------------+
12 rows in set (0.00 sec)

4) Head and tail functions

1.FIRST_VALUE(expr) function

FIRST_VALUE(expr) The function returns the first expr Value .

give an example : Sort by price , Query the first 1 Price information of a commodity .

mysql> 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);
+----+---------------+------------+---------+-------+-------------+
| id | category      | NAME | price | stock | first_price |
+----+---------------+------------+---------+-------+-------------+
| 5  |  Women's wear / Women's Boutique    |  Pleated skirt  | 29.90 | 500 | 29.90 |
| 1  |  Women's wear / Women's Boutique    | T T-shirt  | 39.90 | 1000 | 29.90 |
| 2  |  Women's wear / Women's Boutique    |  dress  | 79.90 | 2500 | 29.90 |
| 3  |  Women's wear / Women's Boutique    |  fleece  | 89.90 | 1500 | 29.90 |
| 4  |  Women's wear / Women's Boutique    |  A pair of jeans  | 89.90 | 3500 | 29.90 |
| 6  |  Women's wear / Women's Boutique    |  Woolen coat  | 399.90 | 1200 | 29.90 |
| 9  |  Outdoor sports        |  Alpenstocks  | 59.90 | 1500 | 59.90 |
| 7  |  Outdoor sports        |  Bicycle  | 399.90 | 1000 | 59.90 |
| 10 |  Outdoor sports        |  Riding equipment  | 399.90 | 3500 | 59.90 |
| 12 |  Outdoor sports        |  Skate  | 499.90 | 1200 | 59.90 |
| 11 |  Outdoor sports        |  Sport coat  | 799.90 | 500 | 59.90 |
| 8  |  Outdoor sports        |  Mountain Bike  | 1399.90 | 2500 | 59.90 |
+----+---------------+------------+---------+-------+-------------+
12 rows in set (0.00 sec)

LAST_VALUE(expr) function

LAST_VALUE(expr) The function returns the last expr Value .

give an example : Sort by price , Query the price information of the last commodity .

mysql> SELECT id, category, NAME, price, stock,LAST_VALUE(price) OVER w AS last_price
-> FROM goods WINDOW w AS (PARTITION BY category_id ORDER BY price);
+----+---------------+------------+---------+-------+------------+
| id | category      | NAME | price | stock | last_price |
+----+---------------+------------+---------+-------+------------+
| 5  |  Women's wear / Women's Boutique    |  Pleated skirt  | 29.90 | 500 | 29.90 |
| 1  |  Women's wear / Women's Boutique    | T T-shirt  | 39.90 | 1000 | 39.90 |
| 2  |  Women's wear / Women's Boutique    |  dress  | 79.90 | 2500 | 79.90 |
| 3  |  Women's wear / Women's Boutique    |  fleece  | 89.90 | 1500 | 89.90 |
| 4  |  Women's wear / Women's Boutique    |  A pair of jeans  | 89.90 | 3500 | 89.90 |
| 6  |  Women's wear / Women's Boutique    |  Woolen coat  | 399.90 | 1200 | 399.90 |
| 9  |  Outdoor sports        |  Alpenstocks  | 59.90 | 1500 | 59.90 |
| 7  |  Outdoor sports        |  Bicycle  | 399.90 | 1000 | 399.90 |
| 10 |  Outdoor sports        |  Riding equipment  | 399.90 | 3500 | 399.90 |
| 12 |  Outdoor sports        |  Skate  | 499.90 | 1200 | 499.90 |
| 11 |  Outdoor sports        |  Sport coat  | 799.90 | 500 | 799.90 |
| 8  |  Outdoor sports        |  Mountain Bike  | 1399.90 | 2500 | 1399.90 |
+----+---------------+------------+---------+-------+------------+
12 rows in set (0.00 sec)

5) Other functions

1.NTH_VALUE(expr,n) function

NTH_VALUE(expr,n) Function returns the second n individual expr Value . give an example : Inquire about goods Ranked... In the data table 2 And the 3 Price information for .

mysql> SELECT id, category, NAME, price,NTH_VALUE(price,2) OVER w AS second_price,
-> NTH_VALUE(price,3) OVER w AS third_price
-> FROM goods WINDOW w AS (PARTITION BY category_id ORDER BY price);
+----+---------------+------------+---------+--------------+-------------+
| id | category      | NAME       | price   | second_price | third_price |
+----+---------------+------------+---------+--------------+-------------+
| 5  |  Women's wear / Women's Boutique    |  Pleated skirt  | 29.90 | NULL | NULL |
| 1  |  Women's wear / Women's Boutique    | T T-shirt  | 39.90 | 39.90 | NULL |
| 2  |  Women's wear / Women's Boutique    |  dress  | 79.90 | 39.90 | 79.90 |
| 3  |  Women's wear / Women's Boutique    |  fleece  | 89.90 | 39.90 | 79.90 |
| 4  |  Women's wear / Women's Boutique    |  A pair of jeans  | 89.90 | 39.90 | 79.90 |
| 6  |  Women's wear / Women's Boutique    |  Woolen coat  | 399.90 | 39.90 | 79.90 |
| 9  |  Outdoor sports        |  Alpenstocks  | 59.90 | NULL | NULL |
| 7  |  Outdoor sports        |  Bicycle  | 399.90 | 399.90 | 399.90 |
| 10 |  Outdoor sports        |  Riding equipment  | 399.90 | 399.90 | 399.90 |
| 12 |  Outdoor sports        |  Skate  | 499.90 | 399.90 | 399.90 |
| 11 |  Outdoor sports        |  Sport coat  | 799.90 | 399.90 | 399.90 |
| 8  |  Outdoor sports        |  Mountain Bike  | 1399.90 | 399.90 | 399.90 |
+----+---------------+------------+---------+--------------+-------------+
12 rows in set (0.00 sec)

2.NTILE(n) function

NTILE(n) The function divides the ordered data in the partition into n A barrel , Record the bucket number .

give an example : take goods The goods in the table are divided into 3 Group .

mysql> SELECT NTILE(3) OVER w AS nt,id, category, NAME, price
-> FROM goods WINDOW w AS (PARTITION BY category_id ORDER BY price);
+----+----+---------------+------------+---------+
| nt | id | category      | NAME       | price |
+----+----+---------------+------------+---------+
| 1  | 5  |  Women's wear / Women's Boutique    |  Pleated skirt  | 29.90 |
| 1  | 1  |  Women's wear / Women's Boutique    | T T-shirt  | 39.90 |
| 2  | 2  |  Women's wear / Women's Boutique    |  dress  | 79.90 |
| 2  | 3  |  Women's wear / Women's Boutique    |  fleece  | 89.90 |
| 3  | 4  |  Women's wear / Women's Boutique    |  A pair of jeans  | 89.90 |
| 3  | 6  |  Women's wear / Women's Boutique    |  Woolen coat  | 399.90 |
| 1  | 9  |  Outdoor sports        |  Alpenstocks  | 59.90 |
| 1  | 7  |  Outdoor sports        |  Bicycle  | 399.90 |
| 2  | 10 |  Outdoor sports        |  Riding equipment  | 399.90 |
| 2  | 12 |  Outdoor sports        |  Skate  | 499.90 |
| 3  | 11 |  Outdoor sports        |  Sport coat  | 799.90 |
| 3  | 8  |  Outdoor sports        |  Mountain Bike  | 1399.90 |
+----+----+---------------+------------+---------+
12 rows in set (0.00 sec)

5) Summary

The characteristic of window function is that it can be grouped , Sort within groups . in addition , The window function does not reduce the rows in the original table because of grouping Count , This is very useful for us to make statistics and sort on the basis of the original table data .

3. New characteristics 2: Common table expression

Common table expression ( Or universal table expression ) Referred to as CTE(Common Table Expressions).CTE Is a named temporary knot Fruit collection , 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 .

1) Common table expressions

The syntax structure of a common table expression is :

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 .

give an example : Query the details of the employee's Department .

mysql> SELECT * FROM departments
-> WHERE department_id IN (
-> SELECT DISTINCT department_id
-> FROM employees
-> );
+---------------+------------------+------------+-------------+
| department_id | department_name  | manager_id | location_id |
+---------------+------------------+------------+-------------+
|     10        | Administration   | 200        | 1700        |
|     20        | Marketing        | 201        | 1800        |
|     30        | Purchasing       | 114        | 1700        |
|     40        | Human Resources  | 203        | 2400        |
|     50        | Shipping         | 121        | 1500        |
|     60        | IT               | 103        | 1400        |
|     70        | Public Relations | 204        | 2700        |
|     80        | Sales            | 145        | 2500        |
|     90        | Executive        | 100        | 1700        |
|     100       | Finance          | 108        | 1700        |
|     110       | Accounting       | 205        | 1700        |
+---------------+------------------+------------+-------------+
11 rows in set (0.00 sec)

This query can also be completed in the form of ordinary common table expressions :

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           |
|      30       | Purchasing       | 114        | 1700        | 30            |
|      50       | Shipping         | 121        | 1500        | 50            |
|      80       | Sales            | 145        | 2500        | 80            |
|      10       | Administration   | 200        | 1700        | 10            |
|      20       | Marketing        | 201        | 1800        | 20            |
|      40       | Human Resources  | 203        | 2400        | 40            |
|      70       | Public Relations | 204        | 2700        | 70            |
|      110      | Accounting       | 205        | 1700        | 110           |
+---------------+------------------+------------+-------------+---------------+
11 rows in set (0.00 sec)

Example illustrate , 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) 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 .

Case study : 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 Down down Belong to .

Let's try to list the information of all employees with subordinate identity with query statement .

If we use the knowledge we have learned before to solve , It's more complicated , At least 4 Only one query can be done :

  • First step , First find the first generation of managers , People who don't take anyone else as their manager , Store the results in a temporary table ;
  • The second step , Find out all the people who take the first generation of managers as managers , Get a subordinate set , Store the results in a temporary table ;
  • The third step , Find all the following people who are managers , Get a subordinate set , Store the results in a temporary table .
  • Step four , Find out who all the following subordinates are managers , Get a result set .

If the result set of step 4 is empty , Then the calculation is over , The result set of the third step is the subordinate set we need , Otherwise, we must continue Go to step 4 , Until the result set is empty . For example, the data table above , You need to go to step five , To get an empty result set . and , Finally, there is the sixth step : Merge the result set of step 3 and step 4 , In this way, we can finally get the result set we need .

If you use a recursive common table expression , It's very simple . Let me introduce the specific 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, The expression is the first Acting manager .
  • Use recursive query in recursive common table expression , Find out who is the manager in this recursive common table expression , And the times The value of the add 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 to say Subordinates . So we get the result set we need .

It seems that here too 3 Step , It's actually a query 3 Parts of , It only needs to be executed once . And there is no need to use temporary tables Save intermediate results , It's much simpler than the method just now .

Code implementation :

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;

All in all , 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 . If you use other query methods , It's more complicated .

3) Summary

The function of common table expression is to replace sub query , And can be quoted many times . Recursive common table expressions have a common root for queries The tree structure data of nodes is very efficient , You can easily handle queries that are difficult to handle by other query methods .

原网站

版权声明
本文为[ThXe]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230205373557.html