MySQL must know will be - views, stored procedures

A view

1, understand the view

A view is a virtual table, and the table containing the data is not the same, only the view contains a query that retrieves data when using dynamic.

SELECT cust_name,cust_contact
FROM customers,orders,orderitems
WHERE customers.cust_id = orders.cust_id
AND orderitems.order_num = orders.order_num
AND  prod_id = 'TNT2';

This example retrieves the customer orders TNT2, no need to know this person must understand the relevant data table structure, and know how to create queries and join the table. In order to retrieve the same data for other products, you must also modify the final WHERE clause.
Now, if you can put the whole query packed into a virtual table called productcustomers of.

SELECT cust_name,cust_contact
FROM productcustomers
WHERE prod_id = 'TNT2';

This is the role of view, productcustomers is a view, as the view, it does not contain any table should have columns or data. It contains a SQL query.

1.1 Application view

Common applications view

  • Reuse SQL statements
  • Simplify complex SQL operation, after writing queries, you can easily reuse it without having to know the details of it to basic queries.
  • Part of the table is used instead of the entire table.
  • Protect data, you can grant access to part with the user, rather than access to the entire table.
  • And change the data format of said views may return underlying table format and representing different data.

After creating the view, the table may be substantially the same way to use them, can SELECT manipulation of view, filter and sort the data, coupled to a different view or view tables, even add and update data.
View is used to view only a facility data stored elsewhere, view itself does not contain data, they return data is retrieved from another table. When you add or change data in these tables, the view returns the changed data.

Performance problems: because the view does not contain data, each time using the view, the query must be handled according to any required to perform a retrieval. If you use multiple links and filters to create a complex view or view nesting, performance will drop to very powerful. Therefore, before using a large number of applications in the deployment of view, you should be tested.

1.2, in view rules and limitations

  • Like the table view must be uniquely named
  • There is no limit to the number of views can be created
  • To create a view, you must have sufficient access rights. These limits are usually granted by the DBA.
  • View can be nested, i.e., may be utilized to retrieve data from other views to query configuration view.
  • ORDER BY can be used in the view, if the view from the SELECT statement retrieves data also contains ORDER BY, ORDER BY then the view will be overwritten.
  • View can not be indexed, you can not have triggers or default values ​​associated with it.
  • View can be used with table, for example, write a SELECT statement joins the tables and views.

2, use the View

Create a view

  • View using CREATE VIEW statement to create
  • Use SHOW CREATE VIEW viewname; to see the statement to create a view
  • Use DROP delete the view, the syntax for the DROP VIEW viewname
  • Updating the view beforehand with the CREATE DROP then, can be directly used CREATE OR REPLACE VIEW. If you want to update the view does not exist, then the second update statement creates a view. If there is, it will replace the original view.

2.1, using a simplified view of the complex coupling

One of the most common view of the application is to hide the complexity of SQL, which usually involves coupling.

MariaDB [course]> CREATE VIEW productcustomers AS
    -> SELECT cust_name,cust_contact,prod_id
    -> FROM customers,orders,orderitems
    -> WHERE customers.cust_id = orders.cust_id
    -> AND orderitems.order_num = orders.order_num;
Query OK, 0 rows affected (0.01 sec)

The example creates a view named productcustomers, which links the three tables, have been ordered to return all customers of any product list.
You can now use this view to be retrieved ordered TNT2 customers:

MariaDB [course]> SELECT cust_name,cust_contact
    -> FROM productcustomers
    -> WHERE prod_id = 'TNT2';
+----------------+--------------+
| cust_name      | cust_contact |
+----------------+--------------+
| Coyote Inc.    | Y Lee        |
| Yosemite Place | Y Sam        |
+----------------+--------------+
2 rows in set (0.00 sec)

Example retrieve the specific data from view by the WHERE clause, MySQL when processing queries, it specifies the WHERE clause in the query has been added to the view in the WHERE clause, to filter the data correctly.
View greatly simplifies the use of complex SQL statements, use the View, you can write a SQL-time basis, and as often as desired.

2.2, using a reformatted view of the data retrieved

Another common use is reformatted view of the data retrieved.

MariaDB [course]> CREATE VIEW vendorlocations AS 
    -> SELECT Concat(RTrim(vend_name),'(',RTrim(vend_country),')')
    ->        AS vend_title
    -> FROM vendors
    -> ORDER BY vend_name;
Query OK, 0 rows affected (0.00 sec)
MariaDB [course]> SELECT * FROM vendorlocations;
+------------------------+
| vend_title             |
+------------------------+
| ACME(USA)              |
| Anvils R Us(USA)       |
| Furball Inc.(USA)      |
| Jet Set(England)       |
| Jouets Et Ours(France) |
| LT Supplies(USA)       |
+------------------------+
6 rows in set (0.00 sec)

2.3, using the Data View filter unwanted

For the general view of the WHERE clause is also useful, for example, you can define customermaillist view, it does not filter the customer's mailbox.

MariaDB [course]> CREATE VIEW  customeremaillist AS 
SELECT cust_id,cust_name,cust_email  
FROM customers 
WHERE cust_email IS NOT NULL;
Query OK, 0 rows affected (0.00 sec)
MariaDB [course]> SELECT * FROM customeremaillist;
+---------+----------------+---------------------+
| cust_id | cust_name      | cust_email          |
+---------+----------------+---------------------+
|   10001 | Coyote Inc.    | ylee@coyote.com     |
|   10003 | Wascals        | rabbit@wascally.com |
|   10004 | Yosemite Place | sam@yosemite.com    |
|   10005 | The Fudds      | fudd@xupt.com       |
+---------+----------------+---------------------+
4 rows in set (0.00 sec)

2.4, calculated using the view field

Simplified view is particularly useful for using the calculated field, look Example:

MariaDB [course]> CREATE VIEW orderitemsexpanded AS 
    -> SELECT order_num,prod_id,quantity,item_price,quantity * item_price AS expanded_price
    -> FROM orderitems;
Query OK, 0 rows affected (0.01 sec)
MariaDB [course]> SELECT *
    -> FROM orderitemsexpanded
    -> WHERE order_num = 20005;
+-----------+---------+----------+------------+----------------+
| order_num | prod_id | quantity | item_price | expanded_price |
+-----------+---------+----------+------------+----------------+
|     20005 | ANV01   |       10 |       5.99 |          59.90 |
|     20005 | ANV02   |        3 |       9.99 |          29.97 |
|     20005 | TNT2    |        5 |      10.00 |          50.00 |
|     20005 | FB      |        1 |      10.00 |          10.00 |
+-----------+---------+----------+------------+----------------+
4 rows in set (0.00 sec)

The view is very easy to create and use a good, proper use can greatly simplify complex data processing.

2.5 update, view

A view is updatable, a view update will update its base table, if on the view by adding or deleting rows or delete rows actually increase its base table. But not all views are updatable, MySQL can not determine if the data is updated correctly, do not allow update.
That is, if the view can not be updated as follows:
packet, coupling, subqueries, and, aggregate functions, DISTINCT, derived columns.
The main purpose view or data retrieval.

3 Summary

View as a virtual table, but the data they contain is not based on a query to retrieve the required data. View provides one kind MySQL SELECT statement-level package, can be used to simplify data processing and reformatting the data base or data base protection.

Second, stored procedures

1 for stored procedures

1.1, the concept of a stored procedure

Stored procedure (Stored Procedure): stored procedure is stored as an executable object in the database or a plurality of SQL commands.

Popular terms: storage process is actually able to complete certain operations of a set of SQL statements. A stored procedure is set to an SQL statement to complete a specific function, created and saved in a database compiled, users can specify the name of the stored procedure and the given parameters (if necessary) to invoke the execution.
Stored Procedures ideology is very simple SQL database language level code reuse and encapsulation.
Namely the implementation of SQL may want to consider intelligent processing contain business rules, including. Not too much of the benefits described packaging operations, nothing is a simplified, multiplexing, and so reducing the coupling, at the same time, it also has higher performance.

1.2, features stored procedure

1. Stored procedure only when creating compiled, each subsequent implementation of the storage process is not need to recompile the general SQL statement is executed once each time the compiler, so the use of stored procedures can improve database speed of execution.
2. When the database complex operations, this package may be complicated operation procedure stored together with the transaction database used in conjunction with supplied.
3. The stored procedure can be reused, you can reduce the workload of database developers.
4. safe, it can be set to only certain users having the right to use the specified stored procedure

2, stored procedures, basic statements

The basic syntax:

--创建存储过程 
CREATE PROCEDURE <存储过程的名称>(<变量的类型定义>)
BEGIN
  <执行操作>
END;

--执行存储过程
CALL <存储过程的名称>(<@变量名>);

--删除存储过程
DROP PROCEDURE <存储过程的名称>;

Creating a simple stored procedure

MariaDB [course]> DELIMITER $$      告诉命令行使用$$作为新的分隔符
MariaDB [course]> CREATE PROCEDURE productpricing()
 BEGIN   
   SELECT AVG(prod_price) AS priceaverage   
   FROM  products; 
 END $$
Query OK, 0 rows affected (0.02 sec)
MariaDB [course]> DELIMITER ;   恢复为原来的语句分隔符

BEGIN and END statements used to define the body of the procedure, the process itself is only a simple SELECT statement.

mysql command-line separator: If the command line to explain the stored procedure itself; characters, components thereof do not become final stored procedure. This causes the stored procedure in SQL syntax errors. The solution is to temporarily change the command-line statement delimiter;

DELIMITER $$
或
DELIMITER //

Call a stored procedure

MariaDB [course]> CALL productpricing();
+--------------+
| priceaverage |
+--------------+
|    16.133571 |
+--------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Delete stored procedure

DROP PROCEDURE roductpricing;

3, the stored procedure with parameters

MySQL stored procedure parameters used in the definition of stored procedures, there are three types of parameters, IN, OUT, INOUT, such as in the form:

CREATEPROCEDURE 存储过程名([[IN |OUT |INOUT ] 参数名 数据类形...])
  • IN Input parameter: indicates an incoming caller to the process value (passed value may be a literal or variable)
  • OUT output parameters: that process outgoing value to the caller (can return multiple values) (Outgoing value can only be variable)
  • INOUT input and output parameters: mean both the caller to process the incoming value, also said that the process of outgoing value to the caller (only value is variable)

Examples of the above procedure stored simply display the results of a SELECT statement. Under normal circumstances, the stored procedure does not display the results, but the results returned to the variable you specify.

CREATE PROCEDURE productpricing(
	OUT p1 DECIMAL(8,2),
	OUT ph DECIMAL(8,2),
	OUT pa DECIMAL(8,2)
)
BEGIN
	SELECT MIN(prod_price)
	INTO p1
	FROM products;
	SELECT MAX(prod_price)
	INTO ph
	FROM products;
	SELECT AVG(prod_price)
	INTO pa 
	FROM products;
END;

Call the stored procedure, you must specify the name of three variables:

CALL productpricing ( @pricelow, @pricehigh, @priceaverage );

This statement does not show any data at the time of call, after it returns to display (or used in other processes) variables.

MariaDB [course]> SELECT @pricehigh,@pricelow,@priceaverage;
+------------+-----------+---------------+
| @pricehigh | @pricelow | @priceaverage |
+------------+-----------+---------------+
|      55.00 |      2.50 |         16.13 |
+------------+-----------+---------------+
1 row in set (0.00 sec)

Examples of the use of a look at the IN and OUT parameter.

MariaDB [course]> CREATE PROCEDURE ordertotal(
 IN onum INT,
 OUT ototal DECIMAL(8,2) )
   BEGIN 
     SELECT SUM(item_price * quantity) 
     FROM orderitems 
     WHERE order_num = onum 
     INTO ototal; 
    END$$
Query OK, 0 rows affected (0.00 sec)
MariaDB [course]> DELIMITER ;

onum defined as IN, because the number of incoming orders from a stored procedure call. ototal defined as OUT, because from the stored procedure returns to the caller. SELECT statement uses these two parameters, WHERE clause uses onum select the correct line, INTO use ototal storage calculated total.

MariaDB [course]> CALL  ordertotal(20005,@total);
Query OK, 1 row affected (0.00 sec)

MariaDB [course]> SELECT @total;
+--------+
| @total |
+--------+
| 149.87 |
+--------+
1 row in set (0.00 sec)

4, the establishment of intelligent storage process

All stored procedures used so far are packaged MySQL simple SELECT statements, although they are all valid examples. But they can complete work directly with these encapsulated statement to complete. Only when that contain business rules and intelligent processing from within a stored procedure, in order to show their true capabilities.
Such a scenario, you need to get the order total as before, but the need for total orders increased sales tax, but only for certain customers.
1, need to get a total. 2, the conditional sales tax added to the total of 3, total return

-- Name: ordertotal
-- Parameters: onumber = order number
--             taxable = 0 if not taxable, 1 if taxable
--             ototal  = order total variable

CREATE PROCEDURE ordertotal(
  IN  onumber INT,
  IN  taxable BOOLEAN,
  OUT ototal DECIMAL(8, 2)
) COMMENT 'Obtain order total, optionally adding tax'
BEGIN
  --Declare variable for total
  DECLARE total DECIMAL(8, 2);
  --Declare tax percentage
  DECLARE taxrate INT DEFAULT 6;
  
  --GET the order total
  SELECT Sum(item_price*quantity)
  FROM orderitems
  WHERE order_num = onumber
  INTO total;

  --Is this taxable
  IF taxable THEN
    SELECT total+(total/100*taxrate) INTO total;
  END IF;
  
  SELECT total INTO ototal;
END;	

DECLAREStored procedures used to define local variables
INTOfor assignment to a variable
IF <boolean> THEN <do something> END IFas conditional execution, remember to END IFending
COMMENTnon-essential, if there is, then SHOW PROCEDURE STATUSdisplayed (Simply put, description similar methods) when the results of
the use --to add SQL statements note


--不含营业税
CALL ordertotal(20005, 0, @total);

SELECT @total
+----------+
|  @total  |
+----------+
|  149.87  |
+----------+

--包含营业税
CALL ordertotal(20005, 1, @total);

SELECT @total
+-----------------+
|      @total     |
+-----------------+
|  158.862200000  |
+-----------------+

5, inspection procedure stored

Display CREATE statement used to create a stored procedure, using SHOW CREATE PROCEDUERstatements.

SHOW CREATE PROCEDURE ordertotal;

In order to display a list of stored procedures, including when and by whom detailed information such as the creation, useSHOW PROCEDURE STATUS;

Published 114 original articles · won praise 30 · views 60000 +

Guess you like

Origin blog.csdn.net/weixin_41476978/article/details/104326152