Mysql views, stored procedures, triggers, functions and Mysql architecture

one, view

The view is a virtual table based on the query, that is, the sql statement is encapsulated, and the view can be called directly when it is used. The table queried by the select statement is called the base table, and the result set of the query is called the virtual table. The basic table data is generated If there is a change, the view will also change, and the view is used to simplify the query statement.

1.CREATE VIEW view_admin AS  SELECT * FROM  admin;  //创建视图
2.    
3. SELECT * FROM  view_admin  //使用视图
4.   
5. DROP VIEW view_admin  //删除视图

2. Stored procedure

1. Overview: We can store some logical business sql statement sets in the database according to some complex requirements of users, and call this set of sql statements by jdbc. This process of writing statements in the database is called storage process.

Calling stored procedures can simplify the work of developers, reduce the transmission between the database and applications, and improve the efficiency of data processing.

2. Syntax: The stored procedure needs to be created first (including business logic), and parameters can be passed into it. There are three types of parameters:

in (input parameter, the value of which must be specified by the calling program)

out (output parameter, the value of the parameter is calculated by the stored procedure and returned to the application)

inout (both output and input)

declare : used to declare variables

The following is a stored procedure without parameters:

1.DELIMITER $$  
2. CREATE PROCEDURE `newsdb`.`a`()  //newsdb为数据库名   a为定义的存储过程名
3.    BEGIN  
4.     DECLARE var_num INT DEFAULT  0;  //声明一个变量,默认为0
5.          SET var_num = 10;  
6.          SELECT var_num;  
7.    END$$  
8.DELIMITER;  

The following are stored procedures with parameters:

DELIMITER$$
CREATE PROCEDURE findUserCount(IN p_type INT,OUT p_count INT)
BEGIN
-- into 把 sql 中查询的结果赋给 变量
SELECT COUNT(*) INTO p_count FROM USER WHERE TYPE = p_type;
SELECT p_count;
END$$
测试
CALL findUserCount(1,@p_count); -- @p_count 测试输出参数

The following are flow control statements:

DELIMITER$$
CREATE PROCEDURE test(IN p_day INT)
BEGIN
IF p_day=0 THEN
SELECT "星期天";
ELSEIF p_day=1 THEN
SELECT "星期一";
ELSEIF p_day=2 THEN
SELECT "星期二";
ELSE
SELECT "无效日期";
END IF;
END$$
测试
CALL test(2)

The following is the case when of the flow control statement

DELIMITER$$
CREATE PROCEDURE test(IN p_day INT)
BEGIN
CASE WHEN p_day = 0 THEN
SELECT "星期天";
ELSE
SELECT "星期一";
END CASE;
END$$
CALL test(2);

3. Function

The parameter list of the function is: parameter name, parameter type

There must be a return statement in the function body, otherwise an error will be reported.

Setup functions can have no parameters

SET GLOBAL log_bin_trust_function_creators=TRUE;

The following functions take no arguments:

#无参的函数
DELIMITER$$
CREATE FUNCTION test() RETURNS INT
BEGIN
DECLARE v_num INT DEFAULT 0;
SELECT COUNT(*) INTO v_num FROM admin;
RETURN v_num;
END$$
#测试
SELECT test(); 

The following are functions with parameters:

#有参的函数
DELIMITER$$
CREATE FUNCTION findnews(p_id INT) RETURNS VARCHAR(20)
BEGIN
DECLARE v_account VARCHAR(20) DEFAULT '';
SELECT account INTO v_account FROM admin WHERE id=p_id;
RETURN v_account;
END$$
#测试
SELECT m.*,findnews(2) FROM newsmessage m

4. Trigger

A trigger is a special stored procedure that does not require the user to call it, but a stored procedure that is executed before or after adding, deleting, or modifying the table.

Triggers are automatically executed and irrevocable. Unlike stored procedures, they cannot be called directly, and cannot pass or receive parameters.

A trigger and the statement that activates it are treated as a single transaction that can be rolled back from anywhere in the trigger.

#触发器
#删除案例,在删除管理员之前删除管理员与角色关联表
DELETE FROM admin WHERE id=4

DELIMITER $$
CREATE TRIGGER delete_admin_role BEFORE DELETE
ON admin
FOR EACH ROW
BEGIN
DELETE FROM admin_role WHERE adminid = old.id;//  old表示原来的数据
END$$;
#新增管理员之前想一个表增加一条信息
DELIMITER $$
CREATE TRIGGER saveadmin AFTER INSERT
ON admin
FOR EACH ROW
BEGIN
INSERT INTO LOGS(account,PASSWORD,oper_time)VALUES(new.account,new.password,NOW());
END$$;   //new表示新增加的数据

INSERT INTO admin(account,PASSWORD)VALUES('jim',111)

Five. Mysql architecture

1. Connection layer: The top layer is some clients and connection services, including local sock communication and most communication similar to tcp/ip based on client/server tools. It mainly completes some similar connection processing, authorization authentication, and related security solutions. That is, it is responsible for the connection request of the client, which can be verified (verify the account password)

2. Service layer: The second layer architecture mainly completes most of the core service functions, such as SQL interface, and completes cached queries, SQL analysis and optimization, and execution of some built-in functions. All cross-storage engine functions are also implemented at this layer, such as procedures and functions. At this layer, the server will parse the query and create a corresponding internal parsing tree, and optimize it accordingly, such as determining the order of the query table, whether to use the index, etc., and finally generate the corresponding execution operation. If it is a select statement, the server will also query the internal cache. If the cache space is large enough, the performance of the system can be greatly improved in the environment of solving a large number of read operations. That is to receive sql, language analysis, optimization, caching.

3. Engine layer: storage engine layer, the storage engine is really responsible for the storage and extraction of data in MysQL, and the server communicates with the storage engine through API. Different storage engines have different functions, so we can choose according to our actual needs. That is, the specific way of real implementation, different storage engines have different characteristics

4. Physical file storage layer: The data storage layer mainly stores data on the file system running on the bare device and completes the interaction with the storage engine.

6. Mysql storage engine

Overview: Data in MySQL is stored in files using a variety of different techniques. Each of these technologies uses different storage mechanisms, indexing techniques, locking levels, and ultimately provides widely different functions and capabilities. By choosing a different technology, you can gain additional speed or functionality, thereby improving the overall functionality of your application. These different technologies and their supporting related functions are called storage engines (also called table types) in MySQL. MySQL comes with a number of different storage engines configured by default, which can be preconfigured or enabled within the MySQL server. You can choose storage engines for servers, databases, and tables that give you maximum flexibility in choosing how to store your information, how to retrieve it, and what performance and functionality you need with your data. The database engine is the core service used to store, process and protect data. Utilize the database engine to control access rights and process transactions quickly, which meets the requirements of most applications in the enterprise that need to process large amounts of data.

Types of storage engines: 1. MyIsam , 2. InnoDB, 3. Memory, 4. Blackhole, 5. CSV, 6.

Performance_Schema, 7. Archive, 8. Federated , 9 Mrg_Myisam

There are two commonly used ones:

1.InnoDB

It is the default, transactional storage engine, with row-level locks and foreign key constraints, and supports full-text retrieval (full-text indexing). Its design goal is to handle large-capacity database systems. When MySQL is running, Innodb will build a buffer pool in memory. Used for buffering data and indexes; supports primary key auto-increment. Does not store the total number of rows in the table

2.Myisam

MyISAM is also the engine of MySQL, but it does not provide support for database transactions, nor does it support row-level locks and foreign keys, so when INSERT (insert) or UPDATE (update) data, the write operation needs to lock the entire table, and the efficiency will be reduced. Lower; supports full-text search; stores the total number of rows in the table. It is mainly used for scenarios with few additions and deletions and many queries

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/129229461