MySQL Basics (03): System and custom functions summarize that triggers Detailed

This article Source: GitHub · Click here || GitEE · Click here

First, the system function package

MySQL has many built-in functions, you can quickly solve business needs to develop some, probably including process control functions, numeric functions, string functions, date and time functions, aggregate functions and so on. The following lists the functions commonly used in these classifications.

1, the control flow function

  • case...when

The value of the return value, determination analog IF-ELSE programming.

-- DEMO 01
SELECT CASE DATE_FORMAT(NOW(),'%Y-%m-%d') 
    WHEN '2019-12-29' THEN 'today' 
    WHEN '2019-12-28' THEN 'yesterday' 
    WHEN '2019-12-30' THEN 'tommor' 
    ELSE 'Unknow' END;
-- DEMO 02
SELECT (CASE WHEN 1>0 THEN 'true' ELSE 'false' END) AS result;
  • if(expr1,expr2,expr3)

If the expression expr1 is TRUE, the IF () returns a value of expr2; otherwise the return value was expr3.

SELECT IF(1>2,'1>2','1<2') AS result ; 
SELECT IF(1<2,'yes ','no') AS result ;
SELECT IF(STRCMP('test','test'),'no','yes');
  • ifnull(expr1,expr2)

If the expression expr1 is not NULL, the return value of expr1; otherwise it returns the value of expr2.

SELECT IFNULL(NULL,'cicada');
SELECT IFNULL(1/1,'no');

2, common string functions

  • CHAR_LENGTH()

Returns the value of the length of the string.

SELECT CHAR_LENGTH(' c i c ') ;-- 包含空格
SELECT LENGTH(' S q l ') ;
  • CONCAT(str1...)

Mosaic series string.

SELECT CONCAT('My', 'S', 'ql');
SELECT CONCAT('My', NULL, 'QL'); -- 包含Null 则返回Null
SELECT CONCAT("%", "Java", "%"); -- mybatis中拼接模糊查询
  • ELT(N,str1,str2,...)

If N = 1, the value is returned str1, if N = 2, the value is returned str2, and so on, can be used to convert the state to return the page.

SELECT ELT(1,'提交','审核中','规则通过') ;
SELECT ELT(2,'提交','审核中','规则通过') ;
  • FORMAT(X,D)

Formatting numeric types.

SELECT FORMAT(3.1455,2) ; -- 四舍五入保留两位
SELECT TRUNCATE(3.1455,2) ; -- 直接截取两位
  • TRIM(str)

Empty string space.

SELECT LTRIM('  hel l o ') ;-- 清空左边
SELECT RTRIM('  hel l o ') ;-- 清空右边
SELECT TRIM('  hel l o ') ; -- 清空两边
SELECT REPLACE('M y S Q L',' ','') ; -- 替换掉全部空格

3, numerical functions

  • FLOOR(X)

Returns the maximum integer value not greater than X,.

SELECT FLOOR(1.23); -- 1
SELECT FLOOR(-1.23); -- -2
  • MOD(N,M)

Mode operation. Back M N are the remainder after the addition.

SELECT MOD(29,9); -- 2
SELECT 29 MOD 9; -- 2
  • RAND() RAND(N)

Returns a random floating point values ​​in the range between 0 and 1. If you have specified an integer parameter N, then it is used as a seed value for generating a repeating sequence.

SELECT RAND(); -- 0.923
SELECT RAND(20) = RAND(20) ; -- TRUE

4, the date and time functions

  • ADDDATE(date,INTERVAL expr type)

To the designated date to specify the type of operation performed.

SELECT DATE_ADD('2019-12-29', INTERVAL 3 DAY); -- 2020-01-01
  • CURDATE ()

The current date by the value 'YYYY-MM-DD' or return format YYYYMMDD format, depending on the function used in a string or numeric context dependent.

SELECT CURDATE(); -- '2019-12-29' 字符串
SELECT CURDATE() + 0; -- 20180725 数字
  • DATE(expr)

Extracting the date or datetime expression expr date part of.

SELECT DATE('2019-12-31 01:02:03'); -- '2019-12-31'
SELECT DATE('2019-12-31 01:02:03')+0; -- 20191231
  • DATE_FORMAT(date,format)

Date value formatted according to the format string.

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d'); -- 2019-12-29
SELECT DATE_FORMAT(NOW(), '%Y年%m月%d日'); -- 2019年12月29日

5, aggregate functions

AVG([distinct] expr)  求平均值
COUNT({*|[distinct] } expr)  统计行的数量
MAX([distinct] expr)  求最大值
MIN([distinct] expr)  求最小值
SUM([distinct] expr)  求累加和

Second, the custom function

1, the concept Introduction

Function stores a series of sql statements, these statements call a function is executed once. So the function can reduce repeat statement. Focus function return values, and triggers focus on the implementation process, some statements can not be executed. So a set of functions is not a simple sql statement.

2, use

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

Format parameter list is: variable name data type.

  • No reference Case
CREATE FUNCTION mysum1 () RETURNS INT RETURN (2+3)*2;
SELECT mysum1 () ;
  • There are function parameters

表结构

CREATE TABLE t01_user (
    id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY  COMMENT '主键ID',
  user_name varchar(20) DEFAULT NULL COMMENT '用户名称'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '用户表';

函数用法

create function get_name(p_id INT) returns VARCHAR(20)
begin 
    declare userName varchar(20);
    select user_name from t01_user where id=p_id into userName;
    return userName;
end;

SELECT get_name(1) ;

3, function View

show create function get_name ;

4, delete function

drop function get_name ;

5, function Notes

Function is compiled in advance, in order to call in a server environment, it needs to be synchronized to compile MySQL Cluster environment; MySQL is multi-threaded environment, so make sure the function is thread-safe.

Third, the flip-flop

1, Introduction to triggers

A trigger is a special stored procedure, except that the stored procedure to use CALL to call, but the trigger does not require the use of CALL. No need to manually start, as long as when a predefined event occurs, it will be automatically triggered calls MYSQL.

2, create a trigger

触发器语法

CREATE TRIGGER trigger_name trigger_time trigger_event 
ON tbl_name FOR EACH ROW trigger_stmt
  • trigger_name: Name the trigger;
  • trigger_time: trigger time action;
  • trigger_event: type of statement that activates the trigger;
  • tbl_name: trigger action suggests that non-temporary tables;
  • trigger_stmt: triggering statement of program execution;

表数据同步

When the user table t01_userwhen data is written simultaneously to t02_backa copy of data written to the table.

-- 用户备份表
CREATE TABLE t02_back (
    id int(11) NOT NULL PRIMARY KEY COMMENT '主键ID',
  user_name varchar(20) DEFAULT NULL COMMENT '用户名称'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT '用户备份';

-- 触发器程序
DROP TRIGGER IF EXISTS user_back_trigger ;
CREATE TRIGGER user_back_trigger AFTER INSERT ON t01_user FOR EACH ROW
BEGIN
    INSERT INTO t02_back (id,user_name)
VALUES (new.id,new.user_name);
END ;

-- 测试案例
INSERT INTO t01_user (user_name) VALUES ('smile'),('mysql') ;
SELECT * FROM t02_back ;

3. Check the trigger

View trigger is a database that already exists in the definition of a trigger, state, grammar information. You can view the information in the trigger TRIGGERS table.

SELECT * FROM `information_schema`.`TRIGGERS` 
WHERE `TRIGGER_NAME`='user_back_trigger';

4, delete the trigger

DROP TRIGGER statement can remove a trigger MYSQL already defined, delete the basic syntax of the trigger.

DROP TRIGGER [schema_name.]trigger_name

5, the flip-flop Notes

  • trigger event

For the same table, the same event can only create a trigger, such as to create two tables t01_user AFTER INSERT trigger, it will error.

  • effectiveness

Trigger the application side can be reduced and the number of communications and business logic of the database, but based on the logical line trigger, if the data set is very large, efficiency is reduced.

  • Affairs issues

Triggers the implementation and execution of the statement whether the original table in the same transaction, depending on whether the trigger table storage engines support transactions.

Fourth, the source address

GitHub·地址
https://github.com/cicadasmile/mysql-data-base
GitEE·地址
https://gitee.com/cicadasmile/mysql-data-base

Guess you like

Origin www.cnblogs.com/cicada-smile/p/12122604.html