MySQL Advanced Chapter 3-Views and Functions

learning target:

  1. Understand the role of views
  2. Familiar with view creation, update, and deletion operations
  3. Familiar with the creation and calling of custom functions
  4. Understand the difference between functions and procedures

Learning Content:

1. View
2. Function


study-time:

2021/2/12


view

Introduction to views:
1) Why use views?
a) From the three paradigms, we know that a table only stores the data of one kind of entity, but the real business often requires the data of multiple tables to be presented in association, and some fixed columns will be frequently accessed. View
Can avoid frequently writing these associated query statements; b) Some people may only allow some columns in the table, and cannot expose the columns or data rows of the entire table. We can create a view for these specific people and give permissions to These people play a role in the security protection of other columns and data rows in the base table; the view stores the sql query statement that can return the result set, when used in the from clause, the internal sql query statement will be executed .


2) What is a view?

A MySQL view is a virtual table whose content is defined by a query. Like a real table, the view contains a series of named column and row data.
However, the view does not exist in the database as a set of stored data values. The 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.
Advantages of the view:

  1. Simplify, what you see is what you get;
  2. Security, users can only query or modify the data they can see;
  3. Logic independence can shield the impact of changes in the real table structure. Disadvantages of the view:
  4. The performance is relatively poor, and querying data from the view may be very slow, especially if the view is created based on other views;
  5. It is inconvenient to modify, especially complex aggregate views cannot be modified.

The use of views in MySQL

1. Create a view based on a single table

Student table creation statement:

DROP TABLE IF EXISTS `studentinfo`;
CREATE TABLE `studentinfo`  (
  `StudentID` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '学号',
  `StudentName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '姓名',
  `Gender` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '性别 默认值为男',
  `Age` int(11) NULL DEFAULT 0 COMMENT '年龄',
  `Birthday` datetime(0) NOT NULL COMMENT '出生日期',
  `StudentNO` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '学员身份证号码唯一约束',
  `ClassID` int(11) NOT NULL DEFAULT 0 COMMENT '班级编号',
  `BeginTime` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '入学时间非空',
  `Phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '电话非空',
  `Province` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '河南' COMMENT '户籍所在省默认值河南',
  `City` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '郑州' COMMENT '户籍所在市',
  `Email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '电子邮件非空',
  `DormitoryNo` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '宿舍号',
  PRIMARY KEY (`StudentID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of studentinfo
-- ----------------------------
INSERT INTO `studentinfo` VALUES ('2011001002', '亡灵战神', '男', 22, '1991-02-21 00:00:00', '410702199102210213', 1, '2011-5-6', '15125741526', '河南', '周口', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001003', '战争女神', '女', 23, '1990-06-21 00:00:00', '410303199006210215', 1, '2011-5-6', '15890172541', '河南', '洛阳', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001004', '黑暗之女', '女', 23, '1990-02-11 00:00:00', '412701199002110618', 1, '2011-5-6', '18637165241', '河南', '周口', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001006', '狂战士', '男', 20, '1990-10-14 00:00:00', '410102199010140317', 1, '2011-5-6', '15569852141', '河南', '郑州', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001008', '正义巨像', '男', 22, '1991-06-21 00:00:00', '410103199106210613', 1, '2011-5-6', '15142153256', '河南', '郑州', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001009', '卡牌大师', '男', 22, '1991-11-15 00:00:00', '410702199111150517', 1, '2011-5-6', '15125741529', '河南', '洛阳', '王[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001010', '德邦总管', '男', 21, '1992-05-06 00:00:00', '410306199205060719', 1, '2011-5-6', '15125471535', '河南', '洛阳', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011001011', '无畏站车', '男', 22, '1991-08-19 00:00:00', '412702199108090103', 1, '2011-5-6', '15125471539', '河南', '周口', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011003001', '诡术妖姬', '女', 22, '1991-11-07 00:00:00', '410106199111070412', 3, '2011-5-6', '18854215874', '河南', '郑州', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011003002', '猩红收割者 ', '女', 18, '1989-06-04 00:00:00', '411303198906040102', 3, '2011-5-6', '17878452365', '河南', '南阳', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011003003', '末日使者', '男', 23, '1990-05-29 00:00:00', '410522199005290213', 3, '2011-5-6', '18878452361', '河南', '安阳', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011003004', '正义天使', '女', 23, '1990-09-16 00:00:00', '410104199009160416', 3, '2011-5-6', '16878452397', '河南', '郑州', '[email protected]', '4102');
INSERT INTO `studentinfo` VALUES ('2011003007', '无极剑圣', '女', 21, '1992-01-07 00:00:00', '410102199201070317', 3, '2011-5-6', '13852417412', '河南', '郑州', '[email protected]', '4102');

  1. Create a view to display the student’s name, gender, age, and class number
create view v_v1 -- view视图的关键词
as -- as后面跟上sql
select 
studentName,Gender,Age,ClassID 
from studentinfo;-- 视图就是有查询组成的
-- 查询视图
select * from v_v1;

operation result:
Insert picture description here

  1. Use the alias view to create a view to display the student’s name, gender, age, and class number, and display it in Chinese
create view v_v2(姓名,性别,年龄,班级) -- view视图的关键词
as -- as后面跟上sql
select 
studentName,Gender,Age,ClassID 
from studentinfo;
-- 查询视图
select * from v_v2;

Insert picture description here


Create a view based on multiple tables

Class table (classinfo):

DROP TABLE IF EXISTS `classinfo`;
CREATE TABLE `classinfo`  (
  `cid` int(11) NOT NULL,
  `canme` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`cid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of classinfo
-- ----------------------------
INSERT INTO `classinfo` VALUES (1, '网开一班');
INSERT INTO `classinfo` VALUES (2, '网开二班');
INSERT INTO `classinfo` VALUES (3, '网开三班');



Create a view to display the student’s name, gender, age, and class name


create view v_v3
as
SELECT
	studentinfo.StudentName,
	studentinfo.Gender,
	studentinfo.Age,
	classinfo.canme
FROM
	classinfo
INNER JOIN studentinfo ON classinfo.cid = studentinfo.ClassID
;

select * from v_v3;-- 视图的数据来源于(基表)

operation result:
Insert picture description here


Use the view to update the data

select * from v_v1;
-- 把v_v1所有的年龄字段都加一
update v_v1 set age=age+1;-- 修改视图、改的是(基表)

Before modification: After
Insert picture description here
modification:
Insert picture description here
Note:
In MySQL, views are not only queryable, but also updatable. This means that you can use INSERT or UPDATE statements to insert or update rows of the base table through an updatable view. In addition, you can use the DELETE statement to delete rows from the underlying table through the view. However, to create an updatable view, the SELECT statement that defines the view cannot contain any of the following elements:

  1. Aggregate function
  2. distinct clause;
  3. group by clause;
  4. having clause;
  5. union and union all clauses;
  6. Outer joins are
    not recommended to use views created based on multiple tables for update operations.

#### WITH CHECK OPTION clause Sometimes, a view is created to display part of the table data. However, simple views are updatable, so data that is not visible through the view can be updated. This update makes the view inconsistent. In order to ensure the consistency of the view, use the WITH CHECK OPTION clause when creating or modifying the view.
create view v_4
as
select * from subject where CreditHour>24;
-- 通过视图查询
select * from v_4;
-- 通过视图添加新课程
insert into v_4 values(null,'java基础 wk22',20,1,1);
-- 查询课程表
select * from v_4;

select * from subject;

View running results:
Insert picture description here
query table structure:
Insert picture description here
here our view and restriction is successful without adding data, but our table has added data, indicating that our data is not synchronized, this is where we need the WITH CHECK OPTION clause

-- 修改视图
alter view v_v4
as
select * from subject where CreditHour>24 with check option;
-- 通过视图添加新课程
insert into v_v4 values(null,'layui',20,1,1);

Insert picture description here
Here we can see that the execution was unsuccessful, indicating that our restriction was successful


function

Function introduction:
The function in MySQL is similar to the function in JavaScript, which is a code block that performs a specific task. In fact, you already have experience in using functions in MySQL. For example, we can use the now() function to obtain the system time, and the avg() function to find the average value. These system-defined functions are called system functions and can be used directly, but sometimes we need to define functions by ourselves when we need to complete specific functions. User-defined functions are called custom functions.

Use of functions in MySQL

Syntax for creating functions

create function 函数名([参数列表]) returns 数据类型
begin
sql 语句;
return;
end;

Exercise:

1. Create a function to return the name of the student whose student ID is "2011001002"

reate function ff1() returns varchar(20)-- returns 返回值类型
begin-- 相当于花括号{}
	declare n varchar(20);-- 定义一个变量
	select 
	studentName into n-- into 赋值 (n)
	from studentinfo 
	where studentID='2011001002';
	return n;-- 返回值
end;
-- 调用函数
select ff1();

Running results:
Insert picture description here
2. Create a function with parameters, enter the student number, and return the student's name

create function ff2(sid varchar(20)) returns varchar(20)
begin
	declare n varchar(20);-- 定义一个变量
	select 
	studentName into n-- into 赋值 (n)
	from studentinfo 
	where studentID=sid;
	return n;-- 返回值
end;
-- 调用函数
select ff2('2011001002');

operation result:
Insert picture description here


#### Note: 1. There is a pair of parentheses after the function name. Parameters can be filled or not filled in the parentheses, but the parentheses cannot be omitted; 2. The parentheses must be followed by returns, and returns must be followed by the return value type. The type must be in MySQL The type of the function; 3. The body of the function is placed in begin..end, before the end, the return value is the same type as the previous returns followed by the return; 4. The select query result can also be used to assign a value to the variable, but the into keyword is required
## to sum up:

The difference between function and procedure:

  1. The return value is different: the function must have a return value and only return one result value; the process can have no return value, but it can return a result set;
  2. The difference in calling: functions are called using select; procedures are called using call;
  3. The difference in parameters: the parameters of the function are all in parameters; the process can pass in\out\inout parameters.

The role of the view:

The SQL query statement that can return the result set is stored in the view. When used in the from clause, the internal SQL query statement will be executed

Limitations of updating the view

**The SELECT statement that defines the view cannot contain any of the following elements: **

1. Aggregate function;
2. distinct clause;
3. group by clause;
4. having clause;
5. union and union all clauses;
6. outer join

Note: It is not recommended to use views created based on multiple tables for update operations.

Note for functions:

  1. There is a pair of parentheses after the function name. Parameters can be filled or not filled in the parentheses, but the parentheses cannot be omitted;

  2. The parentheses must be followed by returns, and returns must be followed by the return value type, which must be the type in MySQL;

  3. The body of the function is placed in begin...end, and the return value before the end is the same as the value of the type followed by the previous returns;

  4. Select query results can also be used to assign values ​​to variables, but the into keyword is required.

The difference between functions and stored procedures

  1. The return value is different: the function must have a return value and only return one result value; the process can have no return value, but it can return a result set;

  2. The difference in calling: functions are called using select; procedures are called using call;

  3. The difference in parameters: the parameters of the function are all in parameters; the process can pass in\out\inout parameters

Guess you like

Origin blog.csdn.net/zhou_yuandong/article/details/114699986