Article directory
- 1. View
-
- 1.1 Basic operations of views
- 1.2 Inspection options for views
- 1.3 View update
- 2. Stored procedures
-
- 2.1 Basic syntax of stored procedures
- 2.2 Variables
-
- 2.2.1 System variables
- 2.2.2 User-defined variables
- 2.2.3 Local variables
- 2.3 Keywords
-
- 2.3.1 Judgment
- 2.3.2 Loop
- 2.4 Cursor
- 2.5 Stored functions
- 3. Trigger
1. View
A 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 and does not save the query results. So when we create a view, the main work falls on creating this SQL query statement.
effect:
- Simple
Views not only simplify users’ understanding of data, but also their operations. Frequently used queries can be defined as views, so that users do not have to specify all the conditions for subsequent operations every time. - Safety
The database can authorize, but cannot authorize to specific rows and columns of the database. Through views, users can only query and modify the data they can see. - Data independence
Views can help users shield the impact of changes in the real table structure
1.1 Basic operations of views
#Create create [or replace] view view name [(column name list)] as select statement [with [cascaded | local] check option]; #Inquire show create view view name; #View the create view statement: select * from view name...; #View view data: #Modification (two options) create [or replace] view view name [(column name list)] as select statement [with [cascaded | local] check option]; alter view view name [(column name list)] as select statement [with [cascaded | local] check option]; #delete drop view [if exists] view name [, view name]..
e.g.
#Create view create or replace view stu_v_1 as select id,name from student where id <= 10; #Query view show create view stu_v_1; select * from stu_v_1; select * from stu_v_1 where id<3; #Modify view create or replace view stu_v_1 as select id,name,num from student where id <= 10; alter view stu_v_1 as select id,name,num from student where id <=10; #Delete view drop view if exists stu_v_1;
1.2 View inspection options
When you create a view using the with check option
clause, MySOL checks each row that is being changed, such as insert, update, delete, through the view to make it conform to the view’s definition.
MySQL allows creating a view based on another view, and it also checks the rules in the dependent view for consistency. To determine the scope of the check, mysql provides two options:
cascaded
and local
, default value is CASCADED
create view v1 as select id,name from student where id <= 20 with cascaded check option; create view v1 as select id,name from student where id <= 20 with local check option;
Cascaded has upward transitivity, that is, a2 is created based on a1, a1 does not have a check option, and a2 does, then a1 will also have this attribute.
local does not
When checking, it will recursively check whether there is a check option and obey the conditions.
1.3 View update
For a view to be updateable, 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 updateable if it contains any of the following:
Aggregation function or window function
: SUM(), MIN(), MAX(), COUNT(), etc.- distinct
- group by
- having
- union or union all
e.g.
#Create a view and use aggregate functions create view stu_v_count as select count(*) from student; insert into stu_v_count vaLues(10); #Error report
#1. In order to ensure the security of the database table, when developers operate the tb_user table, they can only see the basic fields of the user and block the two fields of mobile phone number and email address. 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 stu_name,S.no,c.name cou_name from student S,student_course sc,course c where S.id = Sc.studentid and sc.courseid = c.id;
2. Stored procedure
A stored procedure is a collection of SQL statements that have been compiled in advance and stored in the database. Calling a stored procedure can simplify a lot of work for application developers, reduce the transmission of data between the database and the application server, and is helpful for improving the efficiency of data processing. Benefits.
The concept of stored procedures is very simple. It is code encapsulation and reuse at the SQL language level of the database.
Features:
- Encapsulation, reuse
- Can accept parameters and return data
- Reduce network interaction and improve efficiency
2.1 Basic syntax of stored procedures
#Create create procedure name of the stored procedure ([parameter list]) begin --SQL statement end; #transfer call stored procedure name([parameter]); #Check select * from information_scheme.routines where routine_scheme = 'xxx'; #Query the stored procedures and status information of the specified database show create procedure stored procedure name; #Query the definition of a stored procedure #eg select * from information_schema.routines where routine_schema = '9tse'; #delete drop procedure [if exists] The name of the stored procedure;
If you execute SQL to create a stored procedure on the command line, you need the keyword
delimiter
to specify the end character of the SQL statement.
delimiter $$ create procedure test() begin select count(*) from student; end$$;
2.2 Variables
2.2.1 System variables
System variables are provided by the MySQL server and are not user-defined. They belong to the server level and are divided into global variables (
global
) and session variables (session
).
#View system variables show [session | global] variables; --View all system variables show [session | global] variables like '....'; --You can find variables through like fuzzy matching select @@[session | global] system variable name; --View the value of the specified variable #Set system variables set [session | global] system variable name = value; set @@[session | global] system variable name = value;
PS
- If session/global is not specified,
defaults to session
, session variable - After the MySQL server is restarted, the global parameters set will become invalid. If you want to avoid losing the calibration, you can configure it in
/etc/my.cnf
2.2.2 User-defined variables
User-defined variables are variables defined by users according to their needs. User variables do not need to be declared in advance
. When using them, just use @variable name
directly. Its scope is the current connection
.
#Assignment set @var_name = expr; set @var_name := expr; select @var_name := expr; select field name into @var_name from table name; #use select @var_name;
PS
- User-defined variables do not need to be declared or initialized, but the value obtained is NULL.
- It is recommended to use := to avoid confusion with = (judgment of equality)
set @mygender :='male'; select @mycolor := 'red'; select count(*) into @mycount from tb_user;
2.2.3 Local variables
Local variables are variables that are defined according to and are valid locally
. Before accessing, they need to be declared with DECLARE
. Can be used as local variables and input parameters within stored procedures. The scope of local variables is the begin and end blocks declared within them
#Statement declare variable name variable type [default ...]; The variable type is the database field type: INT, BIGINT, CHAR, VARCHAR, DATE, TIME, etc. #assignment SET variable name = value; SET variable name:=value SELECT field name INTO variable name FROM table name...;
2.3 Keywords
Parameters of stored procedures
Type | Meaning |
---|---|
in (default) | This type of parameter is used as input, that is, the value needs to be passed in when calling |
out | This type of parameter is used as output, that is, this parameter can As a return value |
inout | can be used as an input parameter or an output parameter |
Trigger type | new and old |
---|---|
insert type trigger | new represents data that will be or has been added |
update type trigger | old represents data before modification, new represents Data that will be or has been modified |
delete trigger | . old represents data that will be or has been deleted |
#Create create tigger trigger_name before/after insert/update/delete on tb_name for each row --row-level trigger begin trigger_stmt; end; #Check show triggers; #delete drop trigger [schema_name.]trigger_name; --If schema_name is not specified, it defaults to the current database
e.g.
#Requirements: Record the data change log (user_ogs) of the user table through the server, including add, modify, and delete; #Preparation work: oral log table userlogs create table user_logs( id int(11) not null auto_increment, operation varchar(20) not null comment'operation type, insert/update/delete', operate_time datetime not nul comment'operate time', operate_id int(11) not null comment'operation ID', operate_params varchar(500) comment'operating parameters', primary key('id') )engine=innodb default charset=utf8; 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('insert msg : ' ,new.id,...) end;