Views, indexes, stored procedures, triggers

Views, indexes, stored procedures, triggers

group by added:

According to the specification, in a group query, the selected field can only be a group by field or an aggregate function. Mysql has a small optimization here. After grouping, if all records in a certain field are the same, they can also be selected.

insert image description here

  

  

view

Views are virtual tables . Unlike tables that contain data, views (virtual tables) are queries that retrieve data dynamically .

The role of the view is that if the table structure is too complex, it is not friendly to users who do not understand the table structure. The creator can extract (filter) a batch of data according to the user's needs to become a virtual table for their use. also

After views have been created, they can be utilized in much the same way as tables. You can perform SELECT operations on views, filter and sort data, join views to other views or tables, and even add and update data.

It's important to know that a view is just a facility for viewing data stored elsewhere. Views themselves contain no data, so the data they return is retrieved from other tables. When adding or changing data in these tables, the view will return the changed data.

Because views do not contain data, any retrieval required for query execution must be handled each time a view is used. If you create complex views or nest views with multiple joins and filters, you may find that performance drops dramatically. So don't abuse views.

It is possible to modify the original data through the view, but it is not recommended to do so.

Notice:

  • Like tables, views must be uniquely named (you cannot give a view the same name as another view or table).

  • There is no limit to the number of views that can be created.

  • In order to create a view, sufficient access rights must be available. These restrictions are usually granted by the database administrator.

  • Views can be nested, that is, a view can be constructed from queries that retrieve data from other views.

  • ORDER BY can be used in a view, but if the data retrieved from the view also contains ORDER BY in the SELECT, then the ORDER BY in the view will be overwritten.

  • Views cannot be indexed, and cannot have associated triggers or defaults.

  • Views can be used with tables. For example, write a SELECT statement that joins a table and a view.

Use the command:

  • Views CREATE VIEWare created using statements.

  • Use SHOW CREATE VIEW viewname;to see the statement that created the view.

  • To DROPdelete a view, the syntax is DROP VIEW viewname;.

  • When updating the view, it can be used first DROPand then later CREATE. It can also be used directly CREATE OR REPLACE VIEW. At this time, if the view to be updated does not exist, the update statement will create a view; if the view to be updated exists, the update statement will replace the original view.

Example of use:

#查询订单编号为20005的:产品名称,供应商名称,产品价格,购买数量
SELECT order_num,prod_name, vend_name, prod_price, quantity
FROM orderitems o
         JOIN products p ON o.prod_id = p.prod_id
         JOIN vendors v ON p.vend_id = v.vend_id
WHERE o.order_num = 20005;

# 创建视图,包含所有订单的产品名称,供应商名称,产品价格,购买数量
CREATE VIEW order_detail AS
    SELECT order_num,prod_name, vend_name, prod_price, quantity
FROM orderitems o
         JOIN products p ON o.prod_id = p.prod_id
         JOIN vendors v ON p.vend_id = v.vend_id;

# 查看视图的所有数据
SELECT * FROM order_detail;

# 从视图中过滤数据
SELECT * FROM order_detail WHERE order_num=20005;

# 删除视图
DROP VIEW order_detail; 

  

  

index

Indexes are used to quickly find rows that have a particular value in a column. Without indexes, MySQL must read the entire table starting from the first record until it finds the relevant rows. The larger the table, the more time it takes to query the data, and if the column queried in the table has an index, MySQL can reach it quickly.

An index is a structure that sorts the values ​​of one or more columns in a database. Using an index can improve the query speed of specific data in the database.

An index is a single database structure stored on disk that contains reference pointers to all records in a table. Use indexes to quickly find a value in one or more columns. All MySQL column types can be indexed, and using indexes on related columns is the best way to improve the speed of query operations .

Indexes are implemented in storage engines, so the indexes of each storage engine are not necessarily identical.

  

Indexed categories:

  • Ordinary index and unique index

  Ordinary indexes are the basic type of indexes in MySQL that allow insertion of duplicate and null values ​​in the columns defining the index.

  A unique index requires that the values ​​of the indexed columns must be unique , but null values ​​are allowed . If it is a composite index, the combination of column values ​​must be unique.

  The primary key index is a special index that is unique and does not allow null values. In MySQL, the primary key PRIMARY KEY will automatically create an index, and the unique constraint UNIQUE field will also automatically create an index.

  • Single column index and composite index

A single-column index and an index contains only a single column, and a table can have multiple single-column indexes.

Composite index refers to the index created on the combination of multiple fields of the table. The index will be used only when the left field of these fields is used in the query condition. Follow the leftmost prefix principle when using composite indexes.

  

Use the command:

  • create
--普通索引
CREATE TABLE book(
    id int AUTO_INCREMENT PRIMARY KEY ,
    bookname varchar(255) NOT NULL ,
    INDEX (bookname)   -- 注意
);
--唯一索引
CREATE TABLE book2(
    id int AUTO_INCREMENT PRIMARY KEY ,
    bookname varchar(255) NOT NULL ,
   UNIQUE INDEX (bookname)   -- 注意
); 
-- 给索引起名字
CREATE TABLE book3(
    id int AUTO_INCREMENT PRIMARY KEY ,
    bookname varchar(255) NOT NULL ,
   UNIQUE INDEX  name_idx (bookname)   -- 注意:如果不指定名称的话,名称则为字段名
); 

-- 注意:index 和key是等价的
  • Create indexes separately (not when creating tables)
--普通索引
CREATE INDEX index_name
ON table_name (column_name);
--唯一索引
CREATE UNIQUE INDEX index_name
ON table_name (column_name);
--组合索引
CREATE INDEX index_name
ON table_name (column_name1,column_name2);
  • Delete an index (both ways)
ALTER TABLE table_name DROP INDEX index_name;

DROP INDEX index_name ON table_name; 

  

  

stored procedure

Simply put, a stored procedure is a collection of one or more statements, which can be regarded as a batch file (script), but its role is not limited to batch processing.

  • Basic form
CREATE PROCEDURE  存储过程名 (参数列表)
BEGIN    
  SQL语句代码块
END
  • example one
# 创建存储过程
CREATE PROCEDURE my_test()
BEGIN
    SELECT * FROM book;
END;

# 调用存储过程
CALL my_test();

# 删除存储过程
DROP PROCEDURE my_test;
  • Example two
# 创建存储过程
CREATE PROCEDURE my_test()
BEGIN
#   declare 定义变量i 
    DECLARE i int DEFAULT 0;
    WHILE i<10 do
        INSERT INTO book (bookname) VALUES (concat('悲惨的世界',i));
        SET i=i+1;
    end WHILE ;
END;

  

  

trigger

MySQL triggers, like stored procedures, are programs embedded in MySQL. A trigger is an action triggered by an event, including INSERT, UPDATE, and DELETE statements. If a trigger is defined, when the database executes these statements, the trigger will be fired to perform the corresponding operation. A trigger is a named database object related to a table that will be activated when a specific event occurs on the table.

The trigger is a special stored procedure. The difference is that the execution of the stored procedure needs to be called by the CALL statement, and the execution of the trigger does not need to be called by the CALL statement, nor does it need to be started manually, as long as a predefined event occurs time, it will be automatically called by MySQL.

create:

CREATE TRIGGER trigger_name trigger_time trigger_event
ON tab_name FOR EACH ROW trigger_stmt
  • trigger_name: the name of the trigger, specified by the user;

  • trigger_time : Trigger timing, which can be specified as before or after;

  • trigger_event: Trigger events, including INSERT, UPDATE and DELETE;

  • tab_name: the name of the table to create the trigger;

  • trigger_stmt: The trigger executes the statement.

CREATE TABLE book2(
    id int AUTO_INCREMENT PRIMARY KEY ,
    bookname varchar(255) NOT NULL
);
ALTER TABLE book  ADD INDEX name_idx(bookname);

# 创建触发器,在book表中插入一条数据时自动在book2尾部备份一份新的book
CREATE TRIGGER book_insert_select AFTER INSERT 
ON book FOR EACH ROW INSERT INTO book2(bookname) SELECT bookname FROM book;

INSERT INTO book(bookname)VALUES ('《平凡的世界2》');

# 查看触发器
SHOW TRIGGERS ;

# 也可以在triggers表中查看触发器
SELECT * FROM information_schema.triggers;

# 删除触发器
DROP TRIGGER book_insert_select;

Guess you like

Origin blog.csdn.net/qq_40342400/article/details/129050353