当前位置:网站首页>MySQL | store notes of Master Kong MySQL from introduction to advanced
MySQL | store notes of Master Kong MySQL from introduction to advanced
2022-06-24 08:52:00 【Begonia_ cat】
List of articles
Sort it out again , It is also a process of digestion . Learning must focus on input and output , If you only enter , Most of the time, it's just the brain that understands now , But did not remember . In this way, when actually doing questions or applying , There is no way to write .
Storage Stored
stored procedure and Storage function Sure The complex SQL Logic encapsulated together , Applications There is no need to pay attention to the complex inside of stored procedures and functions SQL Logic , Simply call stored procedures and functions .
1. stored procedure PROCEDURE
thought
- A group passed
PrecompileOf SQL Encapsulation of statements
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 .
advantage :
- It can be compiled and used more than once —— Reduce developer stress
- Good encapsulation —— Reduce mistakes , Increase of efficiency
- Reduce network traffic
- The security of stored procedure is strong —— Reduce SQL The risk of statement exposure
shortcoming :
- Poor portability
- Debugging difficulty
- Version management of stored procedures is difficult
- Not suitable for high concurrency scenarios
Use
- As simple as using functions
The stored procedure did not return a value
(1) Create stored procedure
DELIMITER $ -- New end tag
CREATE PROCEDURE Stored procedure name (IN|OUT|INOUT Parameter name Parameter type , IN|OUT|INOUT Parameter name Parameter type , ...)
[characteristics ...] -- Constraints on stored procedures
--LANGUAGE SQL
--| [NOT] DETERMINISTIC
--| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
--| SQL SECURITY { DEFINER | INVOKER } -- Security level ( The definer can call | If you have permission, you can call ), The default is DEFINER
--| COMMENT 'string'
BEGIN
Query statement
END $
DELIMITER ; -- Restore end tag
- Two common end tags :
$、// SET: Assignment statement , Assign values to variables .SELECT INTO: Store the query result of the assignment statement in the variable , That is, assign values to variables .- Five input parameters
① No parameters ( No parameters, no return )
②IN( Returned by parameter none )
③OUT( No parameters return )
④IN and OUT( There are parameters and returns )
⑤INOUT( There are parameters and returns )
(2) Calling stored procedure
CALL Stored procedure name ( Argument list )
(3) View stored procedures
① View the... Of the stored procedure Create information
SHOW CREATE PROCEDURE Stored procedure name
② View the... Of the stored procedure State information
SHOW PROCEDURE STATUS [LIKE '...']

(4) Modify stored procedure
ALTER PROCEDURE Stored function name
(5) Delete stored procedure
DROP PROCEDURE IF EXIST Stored function name ;
2. Storage function FUNCTION
be used for
Inquire aboutThere is and only one return value
(1) Create a storage function
DELIMITER //
CREATE FUNCTION Stored function name ( Parameter name , Parameter type )
RETURNS return type
# In order to avoid reporting mistakes , You need to add the following three lines
DETERMINISTIC --
CONTAINS SQL -- contain SQL
READS SQL DATA
BEGIN
RETURN(SELECT Query statement );
END //
DELIMITER; -- Reset the end symbol to `;`
or
# To avoid error reporting , Need to add this sentence
SET GLOBAL log_bin_trust_function_creators = 1;
DELIMITER //
CREATE FUNCTION Stored function name ( Parameter name 1 Parameter type , Parameter name 2 Parameter type , ...)
RETURNS return type
BEGIN
RETURN(SELECT Query statement );
END //
DELIMITER; -- Reset the end symbol to `;`
(2) Calling the storage function
SELECT Stored function name (); -- Call function
SET @emp_id := 102; -- Defining variables
# SET @emp_id = 102; `:=` and `=` Fine
SELECT Stored function name (@emp_id); -- Call function
Ingenious notes : because
Storage functionApplicable to query , So call it withSELECT.
(3) Look at the storage functions
① View the storage function Create information
SHOW CREATE FUNCTION Stored function name
② View the storage function State information
SHOW FUNCTION STATUS [LIKE '...']
(4) Modify storage function
ALTER FUNCTION Stored function name
(5) Delete storage function
DROP FUNCTION IF EXIST Stored function name ;
Stored supplemental knowledge
1. Variable
Both assignment symbols are OK , The effect is the same
=:=
(1) System variables
The system variable uses @@ start
Two default values
- compile MySQL The default value of the parameter
my.iniMySQL Parameter values in the configuration file
Modify the value of the system variable
- stay MySQL During service operation , Use
SETCommand to reset the value of the system variable . - modify
my.iniMySQL The configuration file , Then modify MySQL The value of the system variable ( This method needs to be restarted MySQL service )
The default is Session system variables
① Global system variables ( abbreviation : Global variables )
global keyword
max_connections: Only global system variables , Limit the maximum number of connections to the server- See all global variables
SHOW GLOBAL VARIABLES; - View some global variables that meet the conditions
SHOW GLOBAL VARIABLES LIKE '% identifier %'; - View the specified global variables
SELECT @@global. Variable name ;
Assign values to global variables
- The way 1
SELECT @@global. Variable name ; SET GLOBAL Variable name = A variable's value ; - The way 2
SELECT @@global. Variable name ; SET @@global. Variable name = A variable's value ;
② Session system variables ( abbreviation :local Variable )
session keyword
The initial value of the session system variable is the copy of the global system variable value .
pseudo_thread_id: Can only be applied to the current session , Used to mark the current session MySQL Connect ID.View all session variables
SHOW SESSION VARIABLES;orSHOW VARIALBLES;( becauseVariableThe default isSession system variables)Look at some session variables that meet the criteria
SHOW SESSION VARIABLES LIKE '% identifier %';View specified session variables
SELECT @@session. Variable name ;orSELECT @@ Variable name ;
Assign values to session variables
- The way 1
SELECT @@session. Variable name ; SET SESSION Variable name = A variable's value ; - The way 2
SELECT @@session. Variable name ; SET @@session. Variable name = A variable's value ;
(2) User defined variables
User defined variables use @ start : Session user variables ( Don't specify the type ), local variable ( You need to specify the type )
① Session user variables
Definition and assignment ( Need to add
@, There is no need to specify the type )
1. Manual assignmentSET @ User variables = value ; SET @ User variables := value ;2. Fu
Field values in the tableSELECT @ User variables := expression [FROM Wait for words ]; SELECT expression INTO @ User variables [FROM Wait for words ];Scope
Only valid for the current session
Can be added anywhere in the conversationView user variables
SELECT @ User variables
② local variable
Definition ( Type required )
DECLARE Local variable name type [default value ]; # without default Clause , The initial value is NULLassignment ( No need to add
@)
1. Manual assignmentSET Variable name = value SET Variable name := value2. Fu
Field values in the tableSELECT Field name or expression INTO Variable name FROM surface ;Scope
Only in
BEGIN and END Sentence blockEffective in , And can only be placed inThe first sentence.
Can only be used in stored procedures and functionsUsing variables
SELECT Local variable name
DELIMITER //
CLEAR PROVEDURE/FUNCTION Stored procedure name / Stored function name
BEGIN
# Declare local variables
DECLARE Local variable name type DEFAULT The default value is ;
# Assign values to local variables
SET Local variable name = value ;
SELECT Field name INTO Local variable name FROM Table name WHERE filter ;
# View the value of a local variable
SELECT Variable 1, Variable 2, ...;
END
DELIMITER ;
2. “ abnormal ” Handle
In order to avoid stopping the program when it reports an error , You can list the possible errors , When an error occurs , Only report the corresponding error code , And ensure that the program can be successfully executed .
(1) Defined conditions
namely : to Implementation defines the problems that may be encountered during program execution name . Will a Wrong name and Specified error condition Connect .
# MySQL_error_code
DECLARE Error name CONDITION FOR Numeric type error code
# sqlstate_value
DECLARE Error name CONDITION FOR SQLSTATE String type error code
example : stay ERROR 1418(HY000) in :
1418yesMySQL_error_code(Numeric type error code),HY000yessqlstate_value(The length is 5 String type error code)
DECLARE field_Not_Be_NULL CON
(2) The handler
namely : Define what you should do when you encounter a problem , Guarantee Stored procedure or function Continue to execute in case of warnings or errors .
- Enhance the ability of stored programs to deal with problems , Avoid abnormal program stop .
DECLARE Processing mode HANDLER FOR Wrong type Processing statements
Processing mode
CONTINUE: Encounters an errorDon't deal with, Carry on .EXIT: Encounters an errorQuit now
Wrong type
SQLSTATE‘ String error code ’: The length is 5 Of sqlstate_value Error code for typeMySQL_error_code: Match numeric type error codeWrong name: ExpressDECLARE...CONDITIONDefined error condition nameSQLWARNING: Match all to01At the beginningSQLSTATEError code ;NOT FOUND: Match all to02At the beginningSQLSTATEError code ;SQLEXCEPTION: Match all that have not beenSQLWARNINGorNOT FOUNDThe capturedSQLSTATEError code ;
Processing statements SET Variable = value
BEGIN...END
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';
3. Process control
(1) Conditional statements IFCASE
①IF
Use in BEGIN...END in
DELIMITER //
CREATE PROCEDURE/FUNCTION Stored procedure name / Stored function name ()
[ Tagnames :]BEGIN
IF ...
THEN ... -- LEAVE Tagnames
ELSEIF ...
THEN ...
ELSE
END IF;
END //
DELIMITER ;
②CASE
be used for BEGIN...END in
situation 1( Similar to switch)
CASE expression WHEN value 1 THEN result 1 Or words 1( sentence 1 Add... To the end of ;) WHEN value 2 THEN result 2 Or words 2( sentence 1 Add... To the end of ;) ... ELSE result n Or words n( sentence n Add... To the end of ;) END CASEsituation 2( Similar to multiple IF)
CASE WHEN Conditions 1 THEN result 1 Or words 1( sentence 1 Add... To the end of ;) WHEN Conditions 2 THEN result 2 Or words 2( sentence 1 Add... To the end of ;) ... ELSE result n Or words n( sentence n Add... To the end of ;) END CASE
(2) Loop statement LOOPWHILEREPEAT
All three loops can omit the name .
But if you add a loop control statement to the loop (LEAVE or ITERATE), beYou must add a name.
①LOOP( Generally used to implement simple " die " loop .( Usually in combination with LEAVE Use ))
DELIMITER //
CREATE PROCEDURE/FUNCTION Stored procedure name / Stored function name ()
BEGIN
# Defining variables , Used to record the number of cycles
DECLARE loop_count INT DEFAULT 0;
# ① Initialize the loop condition
SELECT ...
[ Tagnames :]Loop
# ② The loop condition ( When to end the cycle )
[IF ... THEN LEAVE [ Tagnames ];
END IF;]
[IF ... THEN ITERATE [ Tagnames ];
END IF;]
# ③ The loop body —— Cycle through the tasks to be completed
... -- Write... According to the requirements of the topic
# ④ Iteration conditions
...; -- Recalculate the cycle condition ( Consistent with initialization cycle conditions )
SET loop_count = loop_count +1; -- cycles +1
END LOOP loop name ;
END //
DELIMITER ;
②WHILE( Judge before you execute )
DELIMITER //
CREATE PROCEDURE/FUNCTION Stored procedure name / Stored function name ()
BEGIN
# ① Initialize the loop condition
# ② The loop condition
[ Tagnames ]:WHILE The loop condition DO
# ③ The loop body
# ④ Iteration conditions
[IF ...
LEAVE Tagnames ;
END IF;]
END WHILE;
END //
DELIMITER ;
③REPEAT( Execute before judge , Unconditionally execute at least once )
DELIMITER //
CREATE PROCEDURE/FUNCTION Stored procedure name / Stored function name ()
BEGIN
REPEAT
loop
UNTIL -- Conditions for ending the cycle . Be careful : This sentence has no `;`
END REPEAT;
END //
DELIMITER ;
(3) Jump statements ITERATELEAVE
①LEAVE Be similar to break
LEAVE Tagnames
②ITERATE Be similar to continue
Can only be used in LOOP/REPEAT/WHILE In loop statement
ITERATE Tagnames
4. trigger
event : A user's action or triggering an action , Include INSERT, UPDATE, DELETE.
When executed INSERT, UPDATE, DELETE When an event is , The trigger will be automatically fired to perform the corresponding operation .
(1) Trigger creation
DELIMITER //
CREATE TRIGGER Trigger Name
{BEFORE|AFTER} {
INSERT|UPDATE|DELETE} ON Table name -- ` Table name ` Objects monitored for triggers
FOR EACH ROW
BEGIN
The block of statements executed by the trigger ;
-- VALUE(NEW. Field name )
-- VALUE(OLD. Field name )
END //
DELIMITER ;
BEFOREIn the event ofBeforeTriggerAFTERIn the event ofafterTriggerINSERTExpressinsert recordTrigger whenUPDATEExpressUpdate recordTrigger whenDELETEExpressDelete recordTrigger whenNEWKeyword is used to call the latestInsertThe data of ( Use inThe block of statements executed by the triggerOfVALUEIn the sentence , Such asVALUE(NEW. Field name )It can be used to view the newly inserted data value of this field .)OLDKeyword is used to call the most recentDeleteThe data of ( Use inThe block of statements executed by the triggerOfVALUEIn the sentence , Such asVALUE(OLD. Field name )It can be used to view the recently deleted data value of this field .)
Verify that the trigger works
notes : In the code above that creates the trigger BEGIN...END In the corresponding
BEGIN
The block of statements executed by the triggerThis statement block can be used to record the operation after triggering in
Designated tablein .
.
such , When an object monitored by a trigger triggers an operation , ThisDesignated tableThe corresponding content will be recorded .
.
adoptSELECT * FROM Designated table ;, You can check whether the trigger is triggered .
END
(2) Check triggers
- Check the... Of the current database
allThe definition of triggerSHOW TRIGGERS - View the current database
SomeThe definition of triggerSHOW CREATE TRIGGER Trigger Name - From the system library
information_schemaOfTRIGGERQuery in table “salary_check_trigger” Trigger informationSELECT * FROM information_schema.TRIGGERS;
(3) Delete trigger
DROP TRIGGER IF EXISTS Trigger Name
(4) Advantages and disadvantages of flip flops
advantage
- Ensure data integrity
- Help us record the operation log
- Before manipulating data , Check the validity of the data
shortcoming
- Poor readability ( Triggers are event driven , Not controlled by the application layer )
- Change of relevant data , May cause trigger errors
- If a foreign key constraint is defined in the child table , And the foreign key specifies DML operation , At this time, modifying the parent table will also cause the corresponding operations of the child table . however , Corresponding based on sub table
The trigger will not be activated.
边栏推荐
- 双指针模拟
- 玄铁E906移植----番外0:玄铁C906仿真环境搭建
- Smart power plant: how to make use of easycvr to build a safe, stable, green and environment-friendly intelligent inspection platform
- 从华为WeAutomate数字机器人论坛,看政企领域的“政务新智理”
- Background management of uniapp hot update
- 520. 检测大写字母
- What is the future development trend of Business Intelligence BI
- Double pointer analog
- 工具类
- Jenkins自动化部署,连接不到所依赖的服务【已解决】
猜你喜欢

阿里资深软件测试工程师推荐测试人员必学——安全测试入门介绍

It is enough to read this article about ETL. Three minutes will let you understand what ETL is

Prompt code when MySQL inserts Chinese data due to character set problems: 1366

One article explains in detail | those things about growth

Xiaohei ai4code code baseline nibble 1

Jenkins自动化部署,连接不到所依赖的服务【已解决】

MySQL | 视图《康师傅MySQL从入门到高级》笔记

一文讲透,商业智能BI未来发展趋势如何

Matlab camera calibrator camera calibration
![[MySQL from introduction to mastery] [advanced part] (I) character set modification and underlying principle](/img/db/e581087e550a2e460f12047685c48f.png)
[MySQL from introduction to mastery] [advanced part] (I) character set modification and underlying principle
随机推荐
520. 检测大写字母
Rsync for file backup
项目部署相关
Send custom events in QT
【使用 PicGo+腾讯云对象存储COS 作为图床】
2138. 将字符串拆分为若干长度为 k 的组
什么是SRE?一文详解SRE运维体系
【E325: ATTENTION】vim编辑时报错
What is the future development trend of Business Intelligence BI
数据中台:中台实践与总结
数据库迁移从PostgreSQL迁移到 MYSQL
leetcode 1642. Furthest building you can reach
DataX User Guide
第七章 操作位和位串(三)
Liunx change the port number of vsftpd
OpenCV每日函数 结构分析和形状描述符(7) 寻找多边形(轮廓)/旋转矩形交集
【LeetCode】415. 字符串相加
MySQL——SQL语句
快慢指针系列
[pytorch basic tutorial 30] code analysis of DSSM twin tower model