MySQL Basics (04): stored procedures and views, usage and characteristics Detailed

This article Source: GitHub · Click here || GitEE · Click here

First, stored procedures

1, the concept Introduction

Stored in the server program is a combination of SQL statements stored, created and saved in the database compiled, executed by the user can invoke the name of the stored procedure. The core idea is to package stored procedures and SQL database language reusability level. Using stored procedures can be less business application system complexity, but will increase the load on the database server system, we need to consider when using the integrated services.

2, the basic syntax

CREATE PROCEDURE sp_name ([proc_parameter[,...]])
    [characteristic ...] routine_body
  • Case I: calculation of consumer discounts
-- 创建存储过程
DROP PROCEDURE IF EXISTS p01_discount ;
CREATE PROCEDURE p01_discount(IN consume NUMERIC(5,2),OUT payfee NUMERIC(5,2))
BEGIN
    -- 判断收费方式
    IF(consume>100.00 AND consume<=300.00) THEN
        SET payfee=consume*0.8;
    ELSEIF (consume>300.00) THEN 
        SET payfee=consume*0.6;
    ELSE 
        SET payfee = consume;
    END IF;
    SELECT payfee AS result;
END ;
-- 调用存储过程
CALL p01_discount(100.0,@discount);
  • Case II: While..Do write data

提供一张数据表

CREATE TABLE `t03_proced` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `temp_name` varchar(20) DEFAULT NULL COMMENT '名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='触发器写数据';

存储程序

The parameters passed, determines the number of data pieces written t03_proced table.

DROP PROCEDURE IF EXISTS p02_batch_add ;
CREATE PROCEDURE p02_batch_add(IN count INT(11))
BEGIN
    DECLARE temp int default 0;
    WHILE temp < count DO
        INSERT INTO t03_proced(temp_name) VALUES ('pro_name');
        SET temp = temp+1 ;
    END WHILE;
END ;

-- 测试:写入10条数据
call p02_batch_add(10);

3 Notes

  • Business scene

Application of stored procedures in the actual development is not very extensive, often complex business scenarios are developed at the application level, you can better manage maintenance and optimization.

  • Speed ​​of execution

In a simple scenario, if a single table of data is written, based applications to write, or write the client database connection, will be much slower compared to the speed of the memory write process, the storage process is not largely communication network overhead, parsing overhead, overhead and other optimizer.

Two, MySQL view

1, the basic concept

The view itself is a virtual table, does not store any data. When using SQL statements to access the view, access to MySQL data is generated from the other tables, views, and tables in the same namespace. View query data is relatively safe, depending on the structure and can hide some of the data, so that users see only the data within the rights, make complex queries easy to understand and use.

2, view usage

Now the basic usage based on user and order management presentation view.

  • The underlying table structure
CREATE TABLE v01_user (
    id INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  user_name VARCHAR(20) DEFAULT NULL COMMENT '用户名',
    phone VARCHAR(20) DEFAULT NULL COMMENT '手机号',
    pass_word VARCHAR(64) DEFAULT NULL COMMENT '密码',
    card_id VARCHAR(18) DEFAULT NULL COMMENT '身份证ID',
    pay_card VARCHAR(25) DEFAULT NULL COMMENT '卡号',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '用户表';

CREATE TABLE v02_order (
    id INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    user_id INT(11) NOT NULL COMMENT '用户ID',
    order_no VARCHAR(32) DEFAULT NULL COMMENT '订单编号',
    good_name VARCHAR(60) DEFAULT NULL COMMENT '商品名称',
    good_id INT(11) DEFAULT NULL COMMENT '商品ID',
    num INT(11) DEFAULT NULL COMMENT '购买数量',
    total_price DECIMAL(10,2) DEFAULT NULL COMMENT '总价格',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '订单表';
  • The basic syntax
CREATE OR REPLACE VIEW view_name 
AS select_statement

Note: the database tables and views share the same namespace, therefore, can not contain database tables and views with the same name.

  • View customer orders
CREATE OR REPLACE 
VIEW user_order_view AS SELECT
    t1.id,t1.user_name,t2.order_no,t2.good_id,
    t2.good_name,t2.num,t2.total_price
FROM v01_user t1
LEFT JOIN v02_order t2 ON t2.user_id = t1.id;
  • View call

Here and MySQL query tables are basically the same, you can use a variety of search criteria.

SELECT * FROM user_order_view WHERE user_name='Cicada';
  • View View
SHOW CREATE VIEW user_order_view ;
  • Modify View
ALTER VIEW view_name AS select_statement ;
  • Delete View
DROP VIEW [IF EXISTS] view_name ;

3, view update

In the case where the specified conditions allow, by operating on the view update, delete, and even the write data, and then updates the relevant table view involved.

UPDATE user_order_view SET user_name='smile' WHERE id='1';

Here the view by performing the update operation, and then update the v01_usertable data. If the aggregate functions view definition, grouping, and other special operations, it can not be updated. MySQL does not support the creation of a trigger on a view.

4, view realization

  • Temporary table algorithm

SQL server will view the query data stored in a temporary table, a view consistent with the structure and the temporary field structure of the table, this is the most taboo SQL query optimization of operations, the amount of data a little too large, it will seriously affect performance. If the view can not produce one mapping between tables and original, it will produce a temporary table, it also shows that the view is not very simple, even very complex functions.

  • Merging algorithm

Server-based table view used to execute the query, the query structure after the final merger returned to the client.

  • Difference method

Execute the following query, analyze performance parameters can be performed.

EXPLAIN SELECT * FROM user_order_view ; 

Query results observed in select_typethe field, if it is DERIVEDthen the use of temporary tables. SQL syntax back here to perform optimization analysis of partial re-explain.

5 Notes

  • Performance issues

MySQL does not support the creation of the index in a view, use the View when query performance may cause a lot of problems, it is recommended to use the time to be careful, multi-angle look at and test.

  • Special Usage

View-based query, you can modify part of the table structure, if not used in the view field, it will not affect the query view.

Third, the source address

GitHub·地址
https://github.com/cicadasmile/mysql-data-base
GitEE·地址
https://gitee.com/cicadasmile/mysql-data-base

Guess you like

Origin www.cnblogs.com/cicada-smile/p/12154620.html