[MySQL | Advanced] 05. Explanation of MySQL views and triggers

Table of contents

1. View

1.1 Introduction

1.2 Grammar

1.2.1 Demonstration example

1.3 Check options

1.3.1 CASCADED cascading

1.3.2 LOCAL local

1.3.3 Example demonstration

1.4 View update

1.4.1 Example demonstration 

1.5 View function

1.6 case

Two, the trigger

2.1 Introduction

2.2 Grammar

2.3 Case

2.3.1 Insert Data Trigger

2.3.2 Modify Data Trigger

2.3.3 Delete data trigger 


1. View

1.1 Introduction

        View (View) is a virtual table. The data in the view does not actually exist in the database. The row and column data come from the tables used in the query of the custom view, and are dynamically generated when the view is used.

        In layman's terms, the view only saves the SQL logic of the query, not the query result. So when we create a view, the main work falls on creating this SQL query statement.

1.2 Grammar

1). Create

CREATE [OR REPLACE] VIEW 视图名称[(列名列表)] AS SELECT语句 [ WITH [CASCADED | LOCAL ] CHECK OPTION ]

2). Query

查看创建视图语句:SHOW CREATE VIEW 视图名称;

查看视图数据:SELECT * FROM 视图名称 ...... ;

3). Modify

# 方式一:
CREATE [OR REPLACE] VIEW 视图名称[(列名列表)] AS SELECT语句 [ WITH[ CASCADED | LOCAL ] CHECK OPTION ]

# 方式二:
ALTER VIEW 视图名称[(列名列表)] AS SELECT语句 [ WITH [ CASCADED |LOCAL ] CHECK OPTION ]

4). Delete

DROP VIEW [IF EXISTS] 视图名称 [,视图名称] ...

1.2.1 Demonstration example

-- 创建视图
create or replace view stu_v_1 as select id,name from student where id <= 10;

-- 查询视图
show create view stu_v_1;

select * from stu_v_1;

select * from stu_v_1 where id < 3;

-- 修改视图
create or replace view stu_v_1 as select id,name,no from student where id <= 10;

alter view stu_v_1 as select id,name from student where id <= 10;


-- 删除视图
drop view if exists stu_v_1;

        We demonstrated above how to create, query, modify, and delete views, so can we insert and update data through views? Next, do a test.

create or replace view stu_v_1 as select id,name from student where id <= 10 ;

select * from stu_v_1;

insert into stu_v_1 values(6,'Tom');

insert into stu_v_1 values(17,'Tom22');

        Execute the above SQL, we will find that the data with id 6 and 17 can be successfully inserted. But when we execute the query, there is no record with id 17 in the query data.

        Because when we created the view, the specified condition was id<=10, and the data with id 17 did not meet the conditions, so it was not queried, but this data has indeed been successfully inserted into the base table. 

        If we specify conditions when we define a view, then when we insert, modify, and delete data, can we operate only when the conditions are met, otherwise we cannot operate? The answer is yes, which requires the help of the inspection option of the view.

1.3 Check options

        When a view is created with the WITH CHECK OPTION clause, MySQL checks each row being changed, such as insert, update, delete, through the view to conform to the view's definition. MySQL allows creating a view based on another view, and it also checks the rules in dependent views for consistency. In order to determine the scope of the check, mysql provides two options: CASCADED and LOCAL, the default value is CASCADED.

1.3.1 CASCADED cascading

        For example, the v2 view is based on the v1 view, if the check option is specified as cascaded when the v2 view is created, but the check option is not specified when the v1 view is created. Then when the check is performed, not only v2 is checked, but v2's associated view v1 is also cascaded.

1.3.2 LOCAL local

        For example, the v2 view is based on the v1 view, if the check option is specified as local when the v2 view is created, but the check option is not specified when the v1 view is created. Then when the check is performed, only v2 will be checked, and the associated view v1 of v2 will not be checked. 

1.3.3 Example demonstration

-- cascaded 选项
create or replace view stu_v_1 as select id,name from student where id <= 15 ;

insert into stu_v_1 values(5,'Tom');

insert into stu_v_1 values(16,'Tom');

# 基于 v1 创建 v2
create or replace view stu_v_2 as select id,name from stu_v_1 where id >= 10 with cascaded check option ;

insert into stu_v_2 values(13,'Tom');

insert into stu_v_2 values(17,'Tom');


create or replace view stu_v_3 as select id,name from stu_v_2 where id < 20 ;

insert into stu_v_3 values(14,'Tom');


-- local 选项
create or replace view stu_v_4 as select id,name from student where id <= 15 with local check option;

insert into stu_v_4 values(5,'Tom');

insert into stu_v_4 values(16,'Tom');


create or replace view stu_v_5 as select id,name from stu_v_4 where id >= 10 with local check option ;

insert into stu_v_5 values(13,'Tom');

insert into stu_v_5 values(17,'Tom');

insert into stu_v_5 values(18,'Tom');

create or replace view stu_v_6 as select id,name from stu_v_5 where id < 20 ;

insert into stu_v_6 values(14,'Tom');

1.4 View update

        For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying table. A view is not updatable if it contains any of the following:

  • Aggregate or window functions (SUM(), MIN(), MAX(), COUNT(), etc.)

  •  DISTINCT

  • GROUP BY

  •  HAVING

  • UNION or UNION ALL

1.4.1 Example demonstration 

-- 创建视图, 使用聚合函数
create view stu_v_count as select count(*) from student;

In the above view, there is only one single row and one column of data. If we update or insert this view, an error will be reported.

insert into stu_v_count values(10);

1.5 View function

1). Simple

        Views not only simplify users' understanding of data, but also their operations. Queries that are frequently used can be defined as views, so that users do not have to specify all the conditions for subsequent operations every time. 

2). Security

        Databases can authorize, but not on specific rows and specific columns of the database. Through views users can only query and modify the data they can see.

3). Data independence

Views can help users shield the impact of real table structure changes.

1.6 case

1). In order to ensure the security of the database table, when the developer operates the tb_user table, he can only see the basic fields of the user, and the two fields of mobile phone number and email address are blocked.

create view tb_user_view as select id,name,profession,age,gender,status,createtime from tb_user;

select * from tb_user_view;

2). Query the courses selected by each student (joint query of three tables). This function is used in many businesses. In order to simplify the operation, define a view.

create view tb_stu_course_view as select s.name student_name , s.no student_no , c.name course_name from student s, student_course sc , course c where s.id = sc.studentid and sc.courseid = c.id;

select * from tb_stu_course_view;

Two, the trigger

2.1 Introduction

        A trigger is a database object related to a table, which triggers and executes a set of SQL statements defined in the trigger before (BEFORE) or after (AFTER) insert/update/delete. This feature of the trigger can assist the application to ensure data integrity, log records, data verification and other operations on the database side.

        Use the aliases OLD and NEW to refer to the changed record content in the trigger, similar to other databases. Currently, triggers only support row-level triggers, not statement-level triggers.

2.2 Grammar

1). Create 

CREATE TRIGGER trigger_name
BEFORE/AFTER INSERT/UPDATE/DELETE
ON tbl_name FOR EACH ROW         -- 行级触发器(指影响了几行的数据则触发器就触发几次)
BEGIN
    trigger_stmt ;
END;

2). View

SHOW TRIGGERS ;

3). Delete

DROP TRIGGER [schema_name.]trigger_name ;     -- 如果没有指定 schema_name,默认为当前数据库 。

2.3 Case

        Record the data change log of the tb_user table through the trigger, and insert the change log into the log table user_logs, including adding, modifying, and deleting.

Table structure preparation:

-- 准备工作 : 日志表 user_logs
create table user_logs(
  id int(11) not null auto_increment,
  operation varchar(20) not null comment '操作类型, insert/update/delete',
  operate_time datetime not null comment '操作时间',
  operate_id int(11) not null comment '操作的ID',
  operate_params varchar(500) comment '操作参数',
  primary key(`id`)
)engine=innodb default charset=utf8;

2.3.1 Insert Data Trigger

-- 插入数据触发器
create trigger tb_user_insert_trigger
    after insert on tb_user for each row
begin
    insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
    (null, 'insert', now(), new.id, concat('插入的数据内容为: id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));
end;

test:

-- 查看
show triggers ;

-- 插入数据到 tb_user
insert into tb_user(id, name, phone, email, profession, age, gender, status, createtime) VALUES (26,'三皇子','18809091212','[email protected]','软件工程',23,'1','1',now());

After the test is complete, check whether the data in the log table can be inserted normally and the correctness of the inserted data.

2.3.2 Modify Data Trigger

create trigger tb_user_update_trigger
    after update on tb_user for each row
begin
    insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
    (null, 'update', now(), new.id,
        concat('更新之前的数据: id=',old.id,',name=',old.name, ', phone=', old.phone, ', email=', old.email, ', profession=', old.profession,
            ' | 更新之后的数据: id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));
end;

test:

show triggers ;

-- 更新
update tb_user set profession = '会计' where id = 23;

update tb_user set profession = '会计' where id <= 5;

After the test is complete, check whether the data in the log table can be inserted normally and the correctness of the inserted data.

2.3.3 Delete data trigger 

create trigger tb_user_delete_trigger
    after delete on tb_user for each row
begin
    insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
    (null, 'delete', now(), old.id,
        concat('删除之前的数据: id=',old.id,',name=',old.name, ', phone=', old.phone, ', email=', old.email, ', profession=', old.profession));
end;

test:

show triggers ;

-- 删除数据
delete from tb_user where id = 26;

-- 删除触发器
drop trigger tb_user_delete_trigger;

After the test is complete, check whether the data in the log table can be inserted normally and the correctness of the inserted data.

Previous article: [MySQL | Advanced] 04. SQL optimization_sql optimization advanced_Stars.Sky's blog-CSDN blog 

Next article: [MySQL | Advanced] 06. Stored Procedure_mysql 02000_Stars.Sky's Blog - CSDN Blog

Guess you like

Origin blog.csdn.net/weixin_46560589/article/details/130219781