MySQL Advanced Query and Programming Notes• [Chapter 5 Common Database Objects]

All chapters >>>>


Contents of this chapter

5.1 View

5.1.1 View definition

5.1.2 Advantages of Views

5.1.3 Creation and use of views

5.1.4 Use views to solve complex applications of the database

5.1.5 Practice exercises

5.2 Index

5.2.1 Basic knowledge of index

5.2.2 Index Classification

5.2.3 Create Index

5.2.4 Practice exercises

5.3 Trigger

5.3.1 Introduction to Triggers

5.3.2 Define trigger

5.3.4 Practice exercises

5.4 Database transaction

5.4.1 Transaction overview

5.4.2 Transaction Features

5.4.3 Turn off MySQL automatic submission

5.4.4 MySQL transaction operation statement

5.4.5 MySQL transaction application

5.4.6 Practice exercises

to sum up:


5.1 View

5.1.1 View definition

A view refers to a view in a computer database. It is a virtual table whose content is defined by the query results.

Like a real table, the view contains a series of named row and column data

The view does not exist in the database as a set of stored data values. Row and column data comes from the table referenced by the query that defines the view, and is dynamically generated when the view is referenced

If the data in the base table changes, the data queried from the view also changes

5.1.2 Advantages of Views

Custom user data (focus on specific data)

  • For example, we can create a view specifically for purchasing personnel. When purchasing personnel query data in the future, they only need to execute "select * from purchasing view".

Simplify data manipulation

  • In the frequent use of more complex query structures, we can query by creating views and simplifying data

Fine-grained safety mechanism

  • The view is virtual, and the data is updated with the update of the base table. The user cannot change and delete the view at will

Combine separated data

  • Using the union keyword, the data of each branch can be combined into one view, which is convenient and efficient

5.1.3 Creation and use of views

grammar:

create view view_name as
select column_name(s) from table_name(s) where condition

view_name: The name of the view.

column_names(s): The list of fields in the view, which can come from multiple tables.

table_name(s): Table name, which can be derived from multiple tables.

condition: Conditional expression. If there are multiple tables, the expression also contains the join conditions of the tables.

Example:

Use Navicat for MySQL tool to create a view. This view is used to view the related information of war-themed movies. It is required to output the movie name, director's name, ticket price, and film length, and display them in ascending order by photo length

Example:

Create a view, which is used to obtain the arrangement of all films, and require output of film name, film length, screening date, screening time and screening hall name, displayed in descending order of screening date and ascending screening time

create view v_schedule_info as
select movieName 电影名 ,filmLength 片长 ,screenDate 放映日期 ,screenTime 放映时间 ,
sh.screeningHall 放映厅 from movie m left join `schedule` s on m.id=s.movieId
left join screening_hall sh on s.hallId=sh.id order by screenDate desc,screenTime

5.1.4 Use views to solve complex applications of the database

Because the columns in the view can be not only the data columns from the base table, but also the expression calculations or aggregate function values ​​based on the data columns of the base table. Therefore, we can use this feature to solve complex database applications

Example:

Create a view that is used to generate the total amount of each customer's booking, and then use this view to update the total amount of each customer's booking

(1) In the ticketing table, group and summarize the total amount of each customer's booking according to the customer number

create view v_calCusFee as select customerID 客户编号 ,sum(purchasePrice) 订票总金额 from ticket_sell group by customerId

(2) The query view v_calCusFee displays the total amount of bookings for all customers

select * from v_calCusFee

(3) Update the totalFee column value of the customer table with the value of the total booking amount in the view v_calCusFee

update customer set totalFee=
(select 订票总金额 from v_calCusFee where 客户编号 =customer.id)

Example:

Encapsulate the detailed ticket purchase data of each customer into a view, and you only need to query the view every time you need to obtain the customer's ticket purchase details

create view v_ticket_purchase as
select username 客户名 ,movieName 电影名 ,screenDate 放映日期 ,screenTime 放映时间 ,
purchasePrice 实际购票价(元)from customer c, `schedule` s, movie m, screening_hall sh, ticket_sell ts 
where c.id=ts.customerId and s.id=ts.scheduleID and s.movieID=m.id and s.hallID=sh.id order by username,screenDate,screenTime

5.1.5 Practice exercises

 

5.2 Index

5.2.1 Basic knowledge of index

  • An index is a structure that sorts the values ​​of one or more columns in a database table (such as the name column of the employee table). If you want to find an employee by the last name of a specific employee, compared to searching all rows in the table, Index helps to get information faster
  • The role of the index is to quickly locate
  • Index is a separate, physical database structure, it depends on the table to establish
  • Indexes provide internal methods for arranging data in tables in the database
  • To some extent, you can think of a database as a book, and an index as a catalog of books. Finding information in a book through the catalog is obviously more convenient and faster than searching on a book without a catalog.

After the index is established, whenever a query request is initiated, the database directly executes the retrieval (search, query) algorithm on the basis of the index, and then quickly finds the corresponding record

Indexing in the database system mainly has the following functions

  • Quickly extract data
  • Ensure the uniqueness of data records
  • Achieve referential integrity between tables
  • When using order by and group by clauses for data retrieval, using indexes can reduce the time for sorting and grouping

Advantages of indexing

  • Greatly speed up data retrieval
  • Create a unique index to ensure the uniqueness of each row of data in the database table
  • Connection between accelerometer and table
  • When using grouping and sorting clauses for data retrieval, it can significantly reduce the time for grouping and sorting in the query

Disadvantages of indexes

  • Index needs to occupy physical space
  • When the data in the table is added, deleted and modified, the database system needs to dynamically maintain the index, which reduces the speed of data maintenance

Because certain system performance will be lost when creating and using indexes, performance and efficiency need to be comprehensively considered in engineering practice to decide whether to create an index and on which columns to create an index. Under normal circumstances, you can create an index based on the following standards

  • On the columns that often need to be searched, you can speed up the search
  • On the column that is the primary key
  • It is often used on the connected columns. These columns are mainly foreign keys. Creating indexes on these columns can speed up the connection
  • Create an index on a column that often needs to be searched according to the range, because the index is sorted and the specified range is continuous
  • Create indexes on columns that often need to be sorted, so that queries can use index sorting, saving time for sorting queries. Create indexes on columns that use the where clause to speed up the judgment of conditions

Generally speaking, columns that should not be indexed have the following characteristics

  • Indexes should not be created for columns that are rarely used or referenced in queries. Due to the increase of the index, it reduces the maintenance speed of the system and increases the space requirement
  • For those columns with few data values, the index should not be added as well. The index should not be added for columns defined as text, image, and bit data types. Because the amount of data in these columns is either quite large or few values
  • When the modification performance is much greater than the retrieval performance, an index should not be created. Because modification performance and retrieval performance are contradictory. When the index is increased, the retrieval performance will be improved, but the modification performance will be reduced. But when the index is reduced, the modification performance will be improved, and the retrieval performance will be reduced

5.2.2 Index Classification

Regular index (Regular Index, also known as ordinary index)

  • It can routinely improve query efficiency. There can be multiple regular indexes in a data table. Conventional index is the most commonly used index type. If the type of index is not clearly specified, the index we are talking about refers to the conventional index

Primary key index (Primary Key, also known as primary key)

  • Can improve query efficiency and provide unique constraints. There can only be one primary key in a table, and the field marked as auto-growth must be the primary key, but the primary key is not necessarily auto-growth

Unique Index (Unique Key)

  • Can improve query efficiency and provide unique constraints. There can be multiple unique indexes in a table

Full Text Index (Full Text, also known as Full Text Search)

  • It is a key technology currently used by search engines. It can intelligently analyze the frequency and importance of keywords in the text by using various algorithms such as word segmentation technology, and then intelligently filter out the search results we want according to certain algorithm rules

Foreign key index (Foreign Key, referred to as foreign key)

  • Can improve query efficiency. If the foreign key field does not specify an index name, it will be automatically generated. The foreign key is automatically associated with the primary key of the corresponding other table, and its main function is to ensure the consistency and integrity of the record

Only InnoDB storage engine tables support foreign keys. The default storage engine of MySQL 5.6 and above is InnoDB.

5.2.3 Create Index

Automatic index creation

  • When MySQL creates other objects in the table, it can create new indexes along with it. Normally, when MySQL creates a unique index constraint or a primary key index constraint, the system will automatically create a unique index and a primary key index on these constraint columns; in addition, the system will usually automatically create a foreign key index on the foreign key column

User create index

  • In addition to MySQL can automatically generate indexes, you can also use the MySQL integrated development platform, such as Navicat For MySQL, or use the SQL statement "create index index name" command to create indexes directly according to actual needs.

Example:

Cinema online ticketing platforms need to display movie information in order of movie prices. In order to improve retrieval efficiency, an index is often created on the ticket price column of the movie table (here "index" is "regular index")

In the blank area of ​​the index editing window, right-click to pop up "Add Index" to add an index

Fill in the index name "idx_ticketPrice" in the "Name" field, drop down the index column "ticketPrice" in the "Column" field, select "Normal" by default for "Index Type" and "BTREE" by default for "Index Method"

1. Use the "alter table add index" command to create an index

grammar:

alter table table_name add index index_name (column_list)
alter table table_name add unique index_name (column_list)
alter table table_name add primary key(column_list)

The above three statements create a common index, a unique index and a primary key index respectively.

table_name is the name of the table whose index needs to be added.

column_list points out which columns to index. When there are multiple columns, the columns are separated by commas. Index name

index_name is optional. By default, MySQL will assign a name based on the first index column.

Example:

Use the alter command to create an index SQL statement on the ticket price column of the movie table (movie)

alter table movie add index idx_ticketPrice(ticketPrice)

SQL statement omitting the index name

alter table movie add index (ticketPrice)

Use the alter command to create a unique index SQL statement on the movie name (movieName) column of the movie table

alter table movie add unique uni_movieName(movieName)

2. Use the "create index" command to create an index

grammar:

create index index_name on table_name (column_list)
create unique index index_name on table_name (column_list)

The table_name, index_name, and column_list have the same meaning as the related words in the "alter table add index" command.

The index name is required.

You cannot use the create index statement to create a primary key index.

Example:

Use the create command to create a unique index on the ticketPrice and movieName columns of the movie table respectively

create index idx_ticketPrice on movie(ticketPrice)
create unique index uni_movieName on movie(movieName)

Use the drop command and the alter command to delete the index command

drop index index_name on table_name
或 alter table table_name drop index index_name

Use the drop command and the alter command to delete the idx_ticketPrice index of the movie table

drop index idx_ticketPrice on movie
或 alter table movie drop index idx_ticketPrice

A composite index refers to an index that contains multiple columns. A composite index is also called a multi-column index or a composite index. The index column can be a single column or multiple columns

Query information about war-themed movies with a ticket price of less than 80 yuan and one of the main actors

select * from movie m, movie_type mt where m.typeID=mt.id and typeName=' 战争 '
and ticketPrice<80 and actors like '% 张涵予 %'

If you only create an index on multiple columns, that is, create a composite index on the ticketPrice column and the actors column, you only need to perform a search to complete the task. The following command will create a composite index idx_ticketPrice_actors on the ticketPrice column and the actors column

create index idx_ticketPrice_actors on movie(ticketPrice,actors)

If indexes are created on multiple columns, MySQL will try to choose the most restrictive index. However, even the most restrictive single-column index, its restrictive capacity is definitely far lower than the composite index created on multiple columns, so the retrieval efficiency of creating a composite index on multiple columns is higher than that in these columns separately Create a single index on the retrieval efficiency.

5.2.4 Practice exercises

 

5.3 Trigger

5.3.1 Introduction to Triggers

Database trigger defines a series of operations, this series of operations is called the trigger program, when a trigger event occurs, the trigger program will run automatically

Triggers are mainly used to monitor the insert, update, and delete data maintenance operations of a table. These maintenance operations can activate the insert, update, or delete triggers of the table to run, thereby realizing automatic data maintenance

The functions that triggers can achieve include: using triggers to implement check constraints, maintain redundant data, and maintain foreign key column data, etc.

Trigger advantages

  • Security: Triggers can give users certain rights to operate the database based on the value of the database; limit user operations based on time; limit user operations based on data in the database
  • Auditing: Triggers can track user operations on the database; audit user operations database statements; write user updates to the database into the audit table
  • Implement complex data integrity rules: triggers can implement non-standard data integrity checks and constraints
  • Implement complex non-standard database-related integrity rules
  • Copy the data in the table synchronously and in real time
  • Provides another way to run scheduled tasks

5.3.2 Define trigger

MySQL syntax for creating triggers

grammar:

create triger 触发器名 触发时间 触发事件 on 表名 for each row
begin
  触发程序
end;

Triggers are database objects, so when creating a trigger, you need to specify which database the trigger belongs to

Triggers are based on the base table, and cannot be based on temporary tables (temporary type tables) and views

There are 3 types of MySQL trigger events: insert, update and delete

There are two trigger timings: before and after for each row, which means row-level triggers

The old keyword and new keyword can be used in the trigger

In the before trigger program, you can use "set new.col_name=value" to change the value of the new record, but in the after trigger program, because the value of the record has been changed, you cannot use "set new.col_name=value" to change it The value of the new record.

In MySQL, you can use triggers to implement check constraint logic

Example:

Use triggers to implement check constraints to ensure that the length of new movies cannot exceed 180 minutes

delimiter $$
drop trigger if exists movie_insert_before_trigger; -- 如果触发器存在,则删除
create trigger movie_insert_before_trigger before insert on movie for each row
begin
-- 如果片长大于 180 分钟
if(new.filmLength>180) then
insert into mytable values(0); -- mytable 表不存在
end if;
end;
$$
delimiter ;

Example:

When the status of "Preferential fare activation" of a movie changes, or the value of "Fare" and "Preferential fare" is changed, use the trigger to realize the cascading update of the corresponding record of the "Actual fare" in the ticketing table value

delimiter $$
drop trigger if exists movie_update_after_trigger;
create trigger movie_update_after_trigger after update on movie for each row
begin
declare _scheduleID int; -- 排片编号
declare state varchar(20);
-- 定义当前发生数据更新的电影所对应的拍片编号的游标
if(new.isActive<>old.isActive||new.ticketPrice<>old.ticketPrice
||new.preferentialPrice<>old.preferentialPrice) then
if(new.isActive=0) then -- 票价没有优惠,实际票价等于票价
update ticket_sell set purchasePrice=new.ticketPrice where scheduleID=_scheduleID;
else -- 票价有优惠,实际票价等于优惠价
update ticket_sell set purchasePrice=new.preferentialPrice
where scheduleID=_scheduleID;
end if;
end if;
end while discount;
close scheduleID_cursor; -- 关闭游标
end
$$
delimiter ;

When modifying records in the trigger program, be especially careful when using the update statement, because this statement will activate the update trigger of the table, which may lead to an infinite loop.

5.3.4 Practice exercises

 

5.4 Database transaction

5.4.1 Transaction overview

In daily life and work, the following problems are often encountered. If customer A and customer B go to the bank for transfer, the intermediate system fails, causing customer A’s account to lose 500 yuan, while customer B’s account does not exceed 500 yuan, which leads to data The inconsistency of the database transaction can solve the problem

A transaction is a complete unit of work defined by the user. All statements in a transaction are executed as a whole, or all executed, or not executed at all

When an error is encountered, the transaction can be rolled back and all changes made within the transaction can be cancelled, thereby ensuring the consistency and recoverability of the data in the database

5.4.2 Transaction Features

Database transactions have four characteristics, referred to as ACID

  • Atomicity (atomic, atomicity): A transaction must be an atomic unit of work. For its data modification, either all of them are executed, or all of them are not executed
  • Consistency (consistent, consistency): When the transaction is completed, all data must be kept in a consistent state, that is, the result of transaction execution must be to transform the database from one consistent state to another consistent state
  • Isolation (isolation): Modifications made by concurrent firms must be isolated from modifications made by any other concurrent firms
  • Durability (duration, durability): After the transaction is completed, its impact on the system is permanent, that is, once the transaction is completed, even if the system has a fatal failure, it will always maintain the modified state

5.4.3 Turn off MySQL automatic submission

By default, MySQL turns on autocommit (autocommit)

This means that any insert statement, update statement and delete statement in the DML, once sent to the MySQL server, the MySQL service instance will immediately parse and execute, and submit the new and updated results to the database file and become the database Permanent data

There are two ways to turn off automatic submission: one is to explicitly turn off automatic submission, and the other is to implicitly turn off automatic submission

Explicitly turn off automatic submission

Implicitly turn off auto-commit

  • Use the MySQL command "start transaction;" to implicitly turn off autocommit, and implicitly turning off autocommit will not modify the value of the system session variable @@autocommit.

5.4.4 MySQL transaction operation statement

  • start transaction: identify the beginning of a transaction, that is, start the transaction
  • commit: Commit the transaction. Mark the end of a transaction, the data modified in the transaction is permanently stored in the database
  • rollback: Roll back the transaction. Identifies the end of a transaction, indicating that an error was encountered during the execution of the transaction, and the data modified in the transaction was rolled back to the state before the execution of the transaction
  • In the actual development process, it is not recommended to use the command "set autocommit=0;" to explicitly close the autocommit, and it is recommended to use the "start transaction;" command. It can not only open new transactions, but also implicitly turn off automatic submission without affecting the value of the system variable @@autocommit

5.4.5 MySQL transaction application

Example:

The customer "Lei Yabo" purchased two items in total, so in addition to generating one record on the Orders table (Orders), two records should also be generated on the Orders Detail table (OrdersDetail)

In other words, you need to perform insert operations on these two tables separately, that is, order maintenance should include these two new operations. They are a business unit and only allow all to succeed. If one of them fails, the two new additions will be cancelled. operating

The use of database transaction technology in the storage process can well achieve the above requirements

delimiter $$
create procedure proc_insertOrdersAndOrdersDetail(
_customerName varchar(20),
_title1 varchar(50),
_quantity1 int,
_title2 varchar(50),
_quantity2 int
)
modifies sql data
begin
declare state varchar(20);
declare _customerID int; -- 客户编号
declare _productID1 int; -- 第 1 件商品编号
declare _productID2 int; -- 第 2 件商品编号
declare _ordersID int; -- 订单编号
declare _ordersDate date default current_date(); -- 订单生成日期,默认为当前日期
-- 定义错误处理
declare continue handler for sqlexception set state='error';
select customerID into _customerID from customer where customerName=_customerName;
start transaction; -- 启动事务
-- 添加订单表记录
insert into orders(customerID,ordersDate) values(_customerID,_ordersDate);
if(state='error') then
select ' 添加订单失败 ';
rollback; -- 回滚事务
else
select max(ordersID) into _ordersID from orders; -- 获取新增订单的订单编号
select productID into _productID1 from product where title=_title1;
-- 添加第 1 件商品到订单明细表
insert into ordersDetail(ordersID,productID,quantity)
values(_ordersID,_productID1,_quantity1);
if(state='error') then
select concat(' 添加 ',title1,' 订单明细失败 ');
rollback;
else
select productID into _productID2 from product where title=_title2;
-- 添加第 2 件商品到订单明细表
insert into ordersDetail(ordersID,productID,quantity)
values(_ordersID,_productID2,_quantity2);
if(state='error') then
select concat(' 添加 ',title2,' 订单明细失败 ');
rollback;
else
select ' 成功添加订单和订单明细数据 ' as 显示结果 ;
commit; -- 提交事务
end if;
end if;
end if;
end
$$
delimiter ;

Example:

Executing the following batch processing will generate an order, the order items of this order are two "Pineapple Pops" and one "Shiseido Feiting", the order time is the current time, and two corresponding order detail records are also generated

set @customerName=' 雷亚波 ';
set @title1=' 菠萝爆肉片 ';
set @quantity1=2;
set @title2=' 资生堂菲婷 ';
set @quantity2=1;
call proc_insertOrdersAndOrdersDetail(@customerName,@title1,@quantity1,@title2,@quantity2);

5.4.6 Practice exercises

 

to sum up:

  • A view is a database object, a virtual table derived from a table, multiple tables or views. The view only stores the definition of the view, not the data corresponding to the view
  • Indexes provide internal methods in the database for arranging data in tables. The role of the index is to quickly locate
  • Triggers are mainly used to monitor the insert, update, and delete data maintenance operations of a table. These maintenance operations can activate the insert, update, or delete triggers of the table to run, thereby realizing automatic data maintenance
  • A transaction is a complete unit of work defined by the user. All statements in a transaction are executed as a whole, or all executed, or not executed at all

 

Guess you like

Origin blog.csdn.net/weixin_44893902/article/details/111125928