Article Directory
view
View concept
View can be simply understood as a virtual table, and it is real different database tables, data view is based on a real table from the query. Have the same real tables and views similar structure. Real table update, query, and delete, view is also supported. So the view is obtained by querying a virtual table, and then saved, the next can be used directly.
View benefits
-
Enhance the security of the real table:
Views are virtual, you can be granted only the permissions users view without granting permission to real tables, serve to protect the real table. -
Customized display data:
based on the same actual table can be customized to show data to the user through the different needs of different views. -
Simplified data manipulation:
suitable for more complex queries using high frequency scenario, may be achieved by the view.
Operation view
Create a view
create view 视图名 【(字段名1,字段名2,..... )】 as select语句的完整代码 ;
创建一个teacger2course的视图
create view teacher2course as
select * from teacher inner join course on teacher.tid = course.teacher_id;
Modify a view
Modify the view, in fact, is to modify the select statement to view it - equivalent to rewrite the select statement;
alter view 视图名 as 新的select语句;
Delete a view
drop view 视图名;
Stressed
1, in the hard disk, view the table structure only files, not data files Table
2, the view is usually used to query, try not to modify the data view
trigger
Triggers are available to programmers and data analysts a way to ensure data integrity, is a special type of stored procedure that is associated with a special event table stored procedure, its execution is not called by the program, nor is started manually, but is triggered by an event, such as when a table operation (insert, delete, update) will be activated to perform it.
Trigger features
- Advantages:
1. The database allows the user based on the value of the database operation has certain rights.
2. You can track user actions on the database.
3. Can trigger a chain updates to the database in the related tables. Triggers can refuse to roll back those changes or damage related to the integrity of the data update attempted to cancel the transaction. When a key is inserted into its external primary key does not match, the trigger will work.
4. A synchronous data table copied in real time.
The automatic calculation of data values, if the value of the data reaches certain requirements, specific treatment is performed.
Trigger operation
Creating Triggers
CREATE TRIGGER 触发器名称
触发时机
触发操作
ON 表名
FOR EACH ROW
触发体
description:
触发器名称:用来表示触发器的名称,可以自己定义,一般见名知意。
触发时机:标识触发器的触发时机,取值是BEFORE或AFTER。
触发操作 :标识触发事件,取值为INSERT,UPDATE和DELETE
表名:标识建立触发器的表名,即在哪张表上建立触发器
触发体:触发器程序体,可以是一句SQL语句,或者用 BEGIN 和 END 包含的多条语句。
Thus, it can create six kinds of triggers, namely: BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE, AFTER INSERT, AFTER UPDATE, AFTER DELETE.
Two of the same type can not be built in a trigger table, so the table can only build up to a flip-flop 6
DELIMITER change separator:
DELIMITER command is used to change the MySQL monitor the separators. The default delimiter is [;], but the stored procedure itself is a collection of command, it must also contain other delimiters. So confusion and conflict between each other, so before you create a stored procedure, we need to change the default character into a completely unrelated symbol, as long as you can without ambiguity with other keywords, it is commonly used [$$]. After you finish creating, and then we respond to it. But need to be reminded: delimiters changed only valid during startup, restart, it will automatically revert to the default state.
#案例
CREATE TABLE cmd (
id INT PRIMARY KEY auto_increment,
USER CHAR (32),
priv CHAR (10),
cmd CHAR (64),
sub_time datetime, #提交时间
success enum ('yes', 'no') #0代表执行失败
);
CREATE TABLE errlog (
id INT PRIMARY KEY auto_increment,
err_cmd CHAR (64),
err_time datetime
);
delimiter $$ # 将mysql默认的结束符由;换成$$
create trigger tri_after_insert_cmd after insert on cmd for each row
begin
if NEW.success = 'no' then # 新记录都会被MySQL封装成NEW对象
insert into errlog(err_cmd,err_time) values(NEW.cmd,NEW.sub_time);
end if;
end $$
delimiter ; # 结束之后记得再改回来,不然后面结束符就都是$$了
# 往表cmd中插入记录,触发触发器,根据IF的条件决定是否插入错误日志
INSERT INTO cmd (
USER,
priv,
cmd,
sub_time,
success
)
VALUES
('linwow','0755','ls -l /etc',NOW(),'yes'),
('linwow','0755','cat /etc/passwd',NOW(),'no'),
('linwow','0755','useradd xxx',NOW(),'no'),
('linwow','0755','ps aux',NOW(),'yes');
# 查询cmd表记录
select * from cmd;
mysql> select * from cmd;
+----+--------+------+-----------------+---------------------+---------+
| id | USER | priv | cmd | sub_time | success |
+----+--------+------+-----------------+---------------------+---------+
| 1 | linwow | 0755 | ls -l /etc | 2019-05-17 15:46:34 | yes |
| 2 | linwow | 0755 | cat /etc/passwd | 2019-05-17 15:46:34 | no |
| 3 | linwow | 0755 | useradd xxx | 2019-05-17 15:46:34 | no |
| 4 | linwow | 0755 | ps aux | 2019-05-17 15:46:34 | yes |
| 5 | linwow | 0755 | ls -l /etc | 2019-05-17 15:48:17 | yes |
| 6 | linwow | 0755 | cat /etc/passwd | 2019-05-17 15:48:17 | no |
| 7 | linwow | 0755 | useradd xxx | 2019-05-17 15:48:17 | no |
| 8 | linwow | 0755 | ps aux | 2019-05-17 15:48:17 | yes |
+----+--------+------+-----------------+---------------------+---------+
# 查询errlog表记录
select * from errlog;
mysql> select * from errlog;
+----+-----------------+---------------------+
| id | err_cmd | err_time |
+----+-----------------+---------------------+
| 1 | cat /etc/passwd | 2019-05-17 15:46:34 |
| 2 | useradd xxx | 2019-05-17 15:46:34 |
+----+-----------------+---------------------+
Delete Trigger
drop trigger tri_after_insert_cmd;
Process Control
Common flow control statements:
if statement
if statement will be evaluated. Depending on whether the condition is satisfied, the execution of different statements.
IF 判断条件 THEN 执行语句
[ELSEIF 判断条件 THEN 执行语句] ...
[ELSE 执行语句]
END IF
case statement
CASE statement is also used for determining the conditions to be more complex than the IF statement is determined.
第一种
CASE 条件判断的变量
WHEN 变量取值 THEN 执行语句
[WHEN 变量取值 THEN 执行语句] ...
[ELSE 执行语句]
END CASE
第二种
CASE
WHEN 变量取值 THEN 执行语句
[WHEN 变量取值 THEN 执行语句] ...
[ELSE 执行语句]
END CASE
while loop
WHILE statement is conditional control loop. But WHILE statement REPEAT statement and it is not the same.
WHILE 循环执行的条件 DO
执行语句
END WHILE
loop loop
LOOP statement may make certain statements executed repeatedly, to achieve a simple loop. But the statement itself is not the end of the loop LOOP statement encountered LEAVE statement, etc. in order to stop the cycle.
LOOP
执行语句
IF 结束条件THEN LEAVE
END LOOP
repeat loop
REPEAT statement is a conditional loop control. When certain conditions are met, it will be out of the loop.
REPEAT
执行语句
UNTIL 结束条件
END REPEAT
if conditional statement
delimiter //
CREATE PROCEDURE proc_if ()
BEGIN
declare i int default 0;
if i = 1 THEN
SELECT 1;
ELSEIF i = 2 THEN
SELECT 2;
ELSE
SELECT 7;
END IF;
END //
delimiter ;
while loop
delimiter //
CREATE PROCEDURE proc_while ()
BEGIN
DECLARE num INT ;
SET num = 0 ;
WHILE num < 10 DO
SELECT
num ;
SET num = num + 1 ;
END WHILE ;
END //
delimiter ;
Custom Functions
Define their own functions, you can perform specific functions. Sometimes in their own custom function when being given ERROR 1418 (HY000), not the Mysql function can not be created, is not opening function, we must first opening function.
mysql> show variables like '%func%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| log_bin_trust_function_creators | OFF |
+---------------------------------+-------+
mysql> set global log_bin_trust_function_creators=1;
mysql> show variables like '%func%';
+---------------------------------+-------+
| Variable_name | Value |
+---------------------------------+-------+
| log_bin_trust_function_creators | ON |
+---------------------------------+-------+
Creating function
create function 函数名(参数列表)
returns 返回值类型
函数体
description:
函数名:应该合法的标识符,并且不应该与已有的关键字冲突。一个函数应该属于 某数据库,可以使用db_name.fun_name的形式执行当前函数所属数据库,否则默 认为当前数据库。
参数列表:可以有一个或者多个函数参数,甚至是没有参数也是可以的。
返回值:指明返回值类类型。
函数体:自定义函数的函数体由多条可用的MySQL语句,流程控制,变量声明等 语句构成。需要指明的是函数体中一定要含有return 返回语句。
call function
select 函数名(参数列表)
Delete function
DROP FUNCTION IF EXISTS 函数名;
# 功能:返回字符串
delimiter $$
create function fun1()
returns varchar(255)
begin
return 'I am a funcation';
end
$$
delimiter ;
# 通过select 函数名来执行函数
select fun1();
mysql> select fun1();
+------------------+
| fun1() |
+------------------+
| I am a funcation |
+------------------+
# 功能:实现两个整数相加
delimiter $$
create function fn_add(a int,b int )
returns int
begin
return a+b;
end
$$
delimiter ;
select fn_add(200,50);
mysql> select fn_add(200,50);
+----------------+
| fn_add(200,50) |
+----------------+
| 250 |
+----------------+
# 删除自定义函数fn_add
drop function if exists fn_add;
Built-in functions
A numerical function
1.abs (x): returns the absolute value
2.ceil (x) or ceiling (x): returns the smallest integer greater than x
3.floor (x): Returns the largest integer less than x
4.mod (x, y): x and y mode Returns
5.rand (): returns a random number between 0-1
6.round (x, y): returns the result parameter x y rounding off decimals
7.truncate (x, y): Returns the number x y bit result is truncated to decimal
8.pi (): returns pi
9.sqrt (x): Returns the square root of x
10.sign (x): Returns the symbol x, n is 1, -1 negative, zero 0
11.pow (x, y), or power (x, y): y x to the power returns
12.exp (x): Returns the power of e x
13.log (x): Returns the natural logarithm of x
14.log10 (x): Returns the logarithm to base 10
15.radians (x): Returns change the angle in radians
16.degrees (x): Returns change the angle in radians
17.sin (x): Returns the sine of x
18.asin (x): Returns the arc sine of x
19.cos (x): Returns the cosine of x
20.acos (x): Returns the inverse cosine of x
21.tan (x): Returns the tangent of x
22.atan (x): Returns the arc tangent of x
23.cot (x): Returns the cotangent of x
Second, String Functions
1.concat (s1, s2 ... sn): The parameter passed into a string
2.insert (str, x, y, insert): starting from the position of str x, y replacement string length of insert
3.lower (str), upper (str): converts a string to uppercase, lowercase
4.left (str, x) right (str, x) returns str left (on the right) x characters, x is null null is returned
5.lpad (str, n, pad) rpad (str, n, pad) of string str filled from the most left (right) with a pad, until the total length of n
6.trim (), ltrim (), rtrim () removed on both sides, left, right spaces
7.replace (str, a, b) replace all strings with a string in the string str b
8.strcmp (s1, s2): If S1 is smaller than S2, return -1; if S1 is greater than S2 returns 1; return 0 if equal (compare the code ASC2)
9.substring (str, x, y) returns the string str starting from the position x, y is the length of the substring
10.length (str): returns the byte length of str included
11.har_length (str): Returns the character length included str
12.concat_ws (x, s1, s2 ...): x using other connection parameters and generates a string
13.repeat (str, count): return str repeat
14.space (N): Returns the empty string of length N
15.locate (substr, str), locate (substr, pos), instr (str, substr), position (substr IN str): Returns a string in the specified position in the string, wherein the location parameters of other functions opposite instr
16.elt (N, str1, str2, str3 ...): Strn return parameters, if the number N is greater than str parameter, returns NULL
17.field (str, str1, str2, str3, ...): str str ... after the return position in the list of the first occurrence, the str or str can not find is null, 0 is returned
Third, the date function
1.curdate (), current_date (): used to obtain the current date in the format 'YYYY-MM-DD'
2.UTC_DATE (): Returns the current world standard time
3.CURTIME (), CURRENT_TIME (): used to obtain the current world, in the format 'HH: MM: SS'
4.UTC_TIME (), CURRENT_TIMESTAMP (), LOCALTIME (), SYSDATE (), NOW (): for acquiring the current date and time format 'YYYY-MM-DD HH: MM: SS'
5.UTC_TIMESTAMP (), UNIX_TIMESTAMP (): Returns a timestamp
6.month (date): Returns the date of the month
7.monthname (date): Returns the name of the date of the month
8.dayname (date): Returns the date of the name date
9.day (date), dayofmonth (date): return 0 or 1-31
10.dayofweek (date): Returns the 1-7, corresponding to Sunday - Saturday
11.dayofyear (date): Returns the 1-365 or 366
12.week (date [, mode]): judgment is the first weeks of the year, mode is arbitrarily defined from the week beginning the week
13.weekofyear (date): counted starting from Monday one week
14.hour (time): Returns the number of hours, may be greater than 24
15.minute (time): Returns the number of minutes
16.second (time): Returns the number of seconds in the time
17.to_days (date): the number of days from 0 to date in the
18.to_secnds (date): The number of seconds from 0 to date in the
19.adddate(date,interval expr unit),adddate(expr,days),date_add(date,interval expr unit),addtime(expr1,expr2) :日期加
20.date_sub (date, interval expr unit), subtime (expr1, expr2): Save Date
21.date_format (date, format): Date Format
The number of days difference between the returns of: 22.datediff (expr1, expr2)
23.timediff (expr1, expr2): Returns the time gap
Fourth, the flow control statements
1. if (value, t, f): If the value is true, then the value of t, otherwise f
2.ifnull (t, f): If t is null, then the value of f
3.case when [value1] then [result1] ... else [default] end: if value1 is true, then the value result1, otherwise default
Fifth, the system information function
1.database (), schema (): Gets the database is in operation
2.version (): Gets the version of the database is operating
3.user (), session_user (), system_user (), current_user (): Gets the current user name @ host
4.connection_id (): Number Display connector
5.inet_aton (ip) addresses into the network address of the string
Sixth, encryption and compression
1.password (): mysql user to encrypt
2.md5 (): user password encryption
3.sha1 (), sha (): hash encryption
4.compress (str): Returns the binary code
Specific reference to the official document: https://dev.mysql.com/doc/refman/5.6/en/func-op-summary-ref.html