Mysql performance tuning (3)

Preface

  The most recent articles are to introduce you to the performance optimization of mysql. In the first two articles, we introduced the related knowledge of index , mainly including: the basic concept of index, the advantages and disadvantages of reference index, the underlying structure of index, the classification and application of index Index design principles and syntax. The next article introduces views and triggers , and introduces the concepts, creation, modification, and viewing and deletion of views and triggers respectively.
  This article will introduce you to the related content of stored procedures and stored functions. This mainly includes the basic concepts of stored procedures, creating, calling, and deleting stored procedures. In addition, it also introduces the declaration, assignment and application of variables in mysql. Finally, I will introduce three loop structures in the stored procedure in mysql. And, to introduce you to the relevant content of the cursor.
  First, I will introduce you to the relevant content of the stored procedure.

One, the stored procedure

1. Overview of stored procedures and stored functions

  Stored procedures and functions are a collection of SQL statements that have been compiled and stored in the database in advance. Calling stored procedures and functions can simplify a lot of work for application developers, reduce data transmission between the database and the application server, and improve data processing. Efficiency comes from benefits.
  In fact, the most critical of stored procedures and stored functions difference is : function must return a value, but not the stored procedure.

  • Function : is a process with a return value;
  • Process : is a function with no return value;

2. Create a stored procedure

  Next, I will introduce the creation syntax of stored procedures.

create procedure procedure_name([proc_parameter[,...]])
begin
	--SQL语句
end;

  We use a case to specifically illustrate the creation of a stored procedure. It is convenient for everyone to better understand the syntax of the stored procedure.

delimiter $
create procedure pro_test1()
begin
	select 'hello mysql';
end $
delimiter ;

  What we need to pay attention to here is: we used a keyword in the case-"delimiter", which is used to declare the delimiter of the SQL statement . This keyword actually tells the mysql interpreter whether the command has ended and whether mysql is executable. Generally by default : delimiter is;. In the command line client, if a line of command ends with a semicolon, then after pressing Enter, mysql will execute the command.

3. Call the stored procedure

  After we create the stored procedure, we can call the stored procedure in mysql. The calling syntax is as follows:

call procedure_name()

4. View the stored procedure

  After we call the stored procedure, we can view the stored procedure in MySQL. The following is the storage view statement as follows:

--首先我们查询db_name数据库中的所有的存储过程;
select name from mysql.proc where db = 'db_name';
--查询存储过程的状态信息
show procedure status;
--查询某个存储过程的定义
show create procedure test.pro_test1 \G;

5. Delete the stored procedure

  Like other mysql statements, stored procedures can be created, viewed, and of course deleted. Next, we introduce the deletion of stored procedures in mysql. The deletion syntax is as follows:

drop procedure [if exists] sp_name;

6. Grammar

  Through the previous introduction, I believe that everyone has a certain understanding of stored procedures. In fact, those who have learned programming can know that stored procedures can also be programmed, which means that we can also use our common when creating stored procedures. The variables, expressions and control structures of the can complete more complex functions.

(1), variables

  • declare
      us first to introduce a stored procedure variable, declare variables with declare keyword. We can define a local variable through declare, but the scope of the variable can only be in the begin...end block. The main syntax is as follows:
declare var_name[,...] type [default value]

  We introduced the syntax of declare, and we illustrate the usage of declare through a case.

delimiter $
create procedure pro_test2()
begin
	declare num int default 5;
	select num+ 10;
end$
delimiter ;
  • Set
      we introduced earlier that declare defines a local variable. Next, we introduce set direct assignment, which can assign constants or assignment expressions. The specific syntax is as follows:
set var_name = expr [, var_name = expr]...

  We introduced the syntax of set, and we illustrate the usage of set through a case.

delimiter $
create procedure pro_test3()
begin
	declare name varchar(20);
	set name = 'mysql';
	select name;
end$
delimiter ;

  Of course, we can use the select...into method to perform assignment operations. Next, we can use a case to illustrate the usage:

delimiter $
create procedure pro_test5()
begin
	declare countnum int;
	select count(*) into countnum from city;
	select countnum;
end$
delimiter ;

(2), if condition judgment

  The previous chapter mainly introduced the variables in the stored procedure, mainly including the definition of a variable declare and the assignment keyword set. Next, I will introduce the judgment statement of the if condition. The grammatical structure is as follows:

if search_condition then statement_list
	[elseif search_condition then statement_list]
	[else statement_list]
end if

  Next, we use a case to show the realization of the if conditional judgment statement. In order to facilitate your understanding, the specific case is as follows:

  According to the defined height variable, determine the body type of the current height.

  • 180 and above——————> tall
  • 170-180 ——————> Standard figure
  • 170 or more——————> average figure

  The specific storage process is as follows:

create procedure pro_test4()
begin
	declare height int default 175;
	declare description varchar(50) default '';
	if height >= 180 then set description = '身材高挑';
	elseif height >= 170 and height < 180 then set description = '标准身材';
	else set description = '一般身材';
end if;
select concat('身高', height, '对应的身材类型为:',description);
end $;

  We can implement stored procedures by calling statements, the specific implementation is as follows:

call pro_test6();

  The specific results are as follows:

(3), transfer parameters

  As we mentioned earlier, stored procedures can also be programmed, as well as functions. We have learned programming languages, whether it is java or c, and functions can pass parameters. The specific syntax format is as follows:

create procedure procedure_name([in/out/inout]参数名 参数类型)

  According to the grammar of passing parameters we just introduced, there are in, out and inout. Therefore, we will introduce the meaning of the three of them next:

  • in : This parameter can be used as an input, that is, the caller needs to pass in a value. Here, if we don't specify it, it is the default value.
  • out : The parameter is used as output, that is, the parameter can be used as a return value
  • inout : can be used as an input parameter or as an output parameter

  It is the height issue we mentioned before to realize the use of in, out and inout respectively. Because of the body type we mentioned earlier, we will not re-describe it.
  First, let us use in to achieve the height problem, the specific implementation statement is as follows:

create procedure pro_test5(in height int)
begin
	declare description varchar(50) default '';
	if height >= 180 then set description = '身材高挑';
	elseif height >= 170 and height < 180 then set description = '标准身材';
	else set description = '一般身材';
end if;
select concat('身高', height, '对应的身材类型为:',description);
end $;

  Next, let us out output to realize the height problem

create procedure pro_test5(in height int, out description varchar(100))
begin
	declare description varchar(50) default '';
	if height >= 180 then set description = '身材高挑';
	elseif height >= 170 and height < 180 then set description = '标准身材';
	else set description = '一般身材';
end if;
end $;

  Next, we call this function

call pro_test5(168, @description)$
select @description$

  What we need to pay attention to here is that a @description keyword appears in the call. Next, I will introduce relevant knowledge to everyone:

  •    @description: This kind of variable should be preceded by the "@" symbol in the variable name. This symbol is called a user session variable, which means that it is effective throughout the session. This is similar to a global variable.
  •   @@global.sort_buffer_size: This kind of "@@" symbol before the variable is called system variable.

(4), case structure

  The if condition judgment was introduced earlier, and then we introduce the case structure judgment. The specific grammatical structure is as follows:

--**方法一**:
case case_value
	when when_value then statement_list
	[when when_value then statement_list]...
	[else statement_list]
end case;
--方法二:
case
	when search_condition then statement_list
	[when search_condition then statement_list]...
	[else statement_list]
end case

  The above is the basic syntax of case. Next, we will illustrate the usage of case through a case; the specific case is as follows:

  Given a month, then calculate the quarter

create procedure pro_test7(mon int)
begin
	declare result varchar(10);
	case
		when mon >=1 and mon <= 3 then
			set result = '第一季度';
		when mon >=4 and mon <= 6 then
			set result = '第二季度';
		when mon >=7 and mon <= 9 then
			set result = '第三季度';
		else 
			set result = '第四季度';
	end case;
	select concat('传递的月份为:', mon, ',计算出的结果为:', result) as content;
end$

(5), while loop

  The conditional format was introduced earlier; including our common if statement and case statement. Next, I will introduce you to loop statements, which mainly include while, repeat and loop functions. First, I will introduce you to the while loop. The specific syntax is as follows:

while search_condition do
	statement_list
end while;

  Next, we use a case to illustrate the usage of case; the specific case is as follows:

  Calculate the value added from 1 to n-accumulation

  The specific implementation is as follows:

create procedure pro_test8(n int)
begin
	declare total int default 0;
	declare num int default 1;
	while num <= n do 
		set total = total + num;
		set num = num + 1;
	end while;
	select total;
end$

(6), repeat structure

  We just introduced the while loop to you, and then we will introduce the repeat structure. The repeat structure is a conditional loop control statement, which exits the loop when the condition is met. Next, I will introduce the difference between the two loop structures of repeat and while:

  • while is executed only when the conditions are met
  • Repeat is to exit the loop when the conditions are met

  The specific syntax is as follows:

repeat 
	statement_lsit
	until search_condition
end repeat;

  Next, we use a case to illustrate the use of repeat; this case is the same as the previous case, so the implementation is as follows:

create procedure pro_test9(n int)
begin
	declare total int default 0;
	repeat
		set total = total + n;
		set n = n - 1;
		until n = 0
	end repeat;
	select total;
end$

(7), loop statement

  We introduce the last type of loop statement loop function. Loop can implement simple loops. The conditions for exiting the loop are defined by other statements, usually using the leave statement. The specific syntax is as follows:

[begin_label:] LOOP
	statement_list
end loop[end_label]

  What we need to pay attention to here is: if you do not add a statement to exit the loop in the statement_list, then the loop statement can be used to implement a simple endless loop.

(8), leave statement

  We just introduced the loop statement, and also mentioned that the loop structure should be used in conjunction with the leave statement, where the leave statement is used to exit the loop in the loop . Generally, it should be used together with begin...end or loop. Next, we use a simple example of loop and leave, the specific implementation is as follows:

create procedure pro_test10(n int)
begin
	declare total int default 0;
	c:loop
		set total = total + n;
		set n = n - 1;
		if n <= 0 then
			leave c;
		end if;
	end loop c;
	select total;
end$

(9), cursor/cursor

  We introduced three loop structures earlier, and let us introduce a particularly important data type: cursor. The cursor is a data type used to store the result set of a query. In stored procedures and functions, the cursor can be used to loop the results. The use of cursor includes cursor declaration, open, fetch and close, the syntax is as follows:

--声明光标:
declare cursor_name cursor for select_statement;
--open光标
open cursor_name;
--fetch光标
fetch cursor_name into var_name [, var_name]...
--close光标
close cursor_name;

  After introducing the basic syntax of cursors, next, we will implement the application of cursors through a case. First we initialize the script, that is, first create a table and insert some data.

create table emp(
	id int(11) not null auto_increment,
	name varchar(50) not null comment '姓名',
	age int(11) comment '年龄',
	salary int(11) comment '薪水',
	primary key(`id`)
)engine=innodb default charset=utf8;
insert into emp(id, name, age, salary) values (null, 'stefan', 16, 28000),(null, 'napoleon', 26, 18000),(null, 'porrty', 18, 8000),(null, '张三', 26, 2600);

  The table is created and data is inserted, and then we can view the data in the emp table and get it row by row for display.

create procedure pro_test11()
begin
	declare e_id int(11);
	declare e_name varchar(50);
	declare e_age int(11);
	declare e_salary int(11),
	declare emp_result cursor for select * from emp;
	declare exit handler for not found set has_data=0;
	open emp_result;
	repeat 
		fetch emp_result into e_id, e_name, e_age, e_salary;
		select concat('id=', e_id, ',name=',e_name, ', age=', e_age, ',薪资为:', e_salary);
		until has_data = 0
	end repeat;
	close emp_result;
end$

  Our stored procedures have all been introduced. Stored procedures are more important and also a very advanced way of writing. I hope you can master them well. Next, I will introduce you to stored functions.

Two, storage function

  Previously introduced the stored procedure, then we introduce the syntax structure of the stored function:

create function function_name([param type ...])
returns type
begin
	...
end;

  We next define a storage function to get the total number of records that meet the condition (city). The next implementation is as follows:

delimiter $
create function count_city(countryId int)
returns int
begin
	declare cnum int;
	select count(*) into cnum from city where country_id = countryId;
	return cnum;
end$
delimiter ;

  Next, we call the storage function, the specific implementation is as follows:

select count_city(1);
select count_city(2);

  Because the storage function is relatively simple, so we are relatively simple in the introduction.

to sum up

  Our recent articles will introduce you to the performance of mysql. In the first two articles, we introduced the related knowledge of indexes and views and triggers respectively . This article introduced you to the contents of stored procedures and stored functions. The introduction of stored procedures mainly includes: basic concepts, creating, calling, and deleting stored procedures. In addition, it also introduces the declaration, assignment, and application of variables in mysql. In addition, it also introduces three loop structures in stored procedures in mysql. Next, I will introduce you to the relevant content of the cursor. Finally, we introduced the syntax of stored functions. Therefore, mysql is a very important skill. Almost every job in the computer needs a mysq skill. Therefore, we need special mastery. Life is endless and struggle is endless. We work hard every day, study hard, constantly improve our abilities, and believe that we will learn something. Come on! ! !

Guess you like

Origin blog.csdn.net/Oliverfly1/article/details/109412113