当前位置:网站首页>MySQL - function
MySQL - function
2022-06-28 01:19:00 【CaraYQ】
Catalog
function
One 、 The function classification :
- One line function : One input one output
(1) Manipulate data objects
(2) Accept parameters and return a result
(3) Change only one line
(4) Each line returns a result
(5) Can be nested
(6) The parameter can be a column or a value - Multiline functions
Basic functions

SELECT
ABS(-123),ABS(32),SIGN(-23),SIGN(43),PI(),CEIL(32.32),CEILING(-43.23),FLOOR(32.32),
FLOOR(-43.23),MOD(12,5)
FROM DUAL;

# When you pass in the same factor , The random numbers returned are the same , This explanation `RAND()` The bottom layer of a function is actually a random number calculated from a factor , It's a pseudo-random number
SELECT RAND(),RAND(),RAND(10),RAND(10),RAND(-1),RAND(-1)
FROM DUAL;

SELECT ROUND(123.556),ROUND(123.456,0),ROUND(123.456,1),ROUND(123.456,2),
ROUND(123.456,-1),ROUND(153.456,-2)
FROM DUAL;

SELECT TRUNCATE(123.456,0),TRUNCATE(123.496,1),TRUNCATE(129.45,-1)
FROM DUAL;

# Single line functions can be nested
SELECT TRUNCATE(ROUND(123.456,2),0)
FROM DUAL;

Angle and radian exchange function

SELECT RADIANS(30),RADIANS(45),RADIANS(60),RADIANS(90),
DEGREES(2*PI()),DEGREES(RADIANS(60))
FROM DUAL;

Trigonometric functions

SELECT SIN(RADIANS(30)),DEGREES(ASIN(1)),TAN(RADIANS(45)),DEGREES(ATAN(1))
FROM DUAL;

Exponents and logarithms

Index :SELECT POW(2,5),POWER(2,4),EXP(2) FROM DUAL;
logarithm :SELECT LN(EXP(2)),LOG(EXP(2)),LOG10(10),LOG2(4) FROM DUAL;
Conversion between bases

CONV(x,f1,f2) take f1 It's binary x convert to f2 Base number , Such as CONV(10,2,8) Is to convert binary 10 Convert to octal , The binary 10 That is to say 2, Conversion to octal is also 2
SELECT BIN(10),HEX(10),OCT(10),CONV(10,10,8)
FROM DUAL;

String function


SELECT ASCII('Abcdfsf'),CHAR_LENGTH('hello'),CHAR_LENGTH(' We '),
LENGTH('hello'),LENGTH(' We ')
LENGTH('hello') One character is stored in one byte , therefore LENGTH('hello') standing 5 Bytes . and UTF-8 Each Chinese character accounts for 3 Bytes , therefore LENGTH(' We ') Occupy 6 Bytes . use LENGTH() This is how many bytes are used to measure the underlying storage ,CHAR_LENGTH() It measures how many characters are in the memory , therefore CHAR_LENGTH('hello'),CHAR_LENGTH(' We ') All for 5.
# String concatenation :xxx worked for yyy
SELECT CONCAT(emp.last_name,' worked for ',mgr.last_name) "details"
FROM employees emp JOIN employees mgr
WHERE emp.`manager_id` = mgr.employee_id;

SELECT CONCAT_WS('-','hello','world','hello','beijing')
FROM DUAL;
String and string are spliced with the first parameter 
If the first argument is an empty string
SELECT CONCAT_WS('','hello','world','hello','beijing')
FROM DUAL;

The effect is the same as CONCAT Method :
SELECT CONCAT('hello','world','hello','beijing')
FROM DUAL;

SELECT INSERT('helloworld',2,3,'aaaaa'),REPLACE('hello','ll','mmm')
FROM DUAL;
The index of the string is from 1 At the beginning ,INSERT('helloworld',2,3,'aaaaa') take helloworld In the Chinese Index 2 Start , Count back 3 Characters ( Including 3 Characters ), Put these characters ( Characters in this range ) Replace with aaaaa.REPLACE('hello','ll','mmm') take hello Medium ll Replace with mmm
SELECT REPLACE('hello','lol','mmm')
FROM DUAL;
If in the future hello Not found in lol, No replacement, no processing, no error reporting , Returns the original string .
SELECT UPPER('HelLo'),LOWER('HelLo')
FROM DUAL;

stay Oracle String is case sensitive , The following code will only find last_name = 'King'; People who ,king and KING Can't find
SELECT last_name,salary
FROM employees
WHERE last_name = 'King';

So you can use UPPER()、LOWER() Change my :
SELECT last_name,salary
FROM employees
WHERE LOWER(last_name) = 'King';
however MySQL There is no such problem in ,MySQL The string is not case sensitive
SELECT LEFT('hello',2),RIGHT('hello',3),RIGHT('hello',13)
FROM DUAL;

# LPAD: Achieve the right alignment effect
# RPAD: Achieve left alignment effect
SELECT employee_id,last_name,LPAD(salary,10,'*')
FROM employees;
LPAD(salary,10,'*') Express salary Occupy 10 position ( The decimal point also counts ), Not enough * stay On the left A filling 
SELECT CONCAT('---',LTRIM(' h el lo '),'***'),
TRIM('oo' FROM 'ooheollo')
FROM DUAL;
TRIM( character string ) Used to remove spaces at the beginning and end of a string ,TRIM('oo' FROM 'ooheollo') Used to remove ooheollo Head and tail oo,LTRIM()、RTRIM() Respectively used to remove the first 、 Trailing space 
SELECT REPEAT('hello',4),LENGTH(SPACE(5)),STRCMP('abc','abe')
FROM DUAL;
SPACE() Used to provide spaces ,STRCMP() Used for string ratio size , return 1 Indicates that the previous string is larger than the following one 
SELECT SUBSTR('hello',2,2),LOCATE('ll','hello')
FROM DUAL;
SUBSTR( character string , Index position ( Intercept starting position , To intercept the character at this position ), The number of intercepts )LOCATE() Where the first string first appears in the second string 
If there is no first string in the second string , return 0
SELECT ELT(2,'a','b','c','d'),FIELD('mm','gg','jj','mm','dd','mm'),
FIND_IN_SET('mm','gg,mm,jj,dd,mm,gg')
FROM DUAL;

SELECT employee_id,NULLIF(LENGTH(first_name),LENGTH(last_name)) "compare"
FROM employees;
NULLIF( character string 1, character string 2) Compare two strings , If equal , Then return to NULL, Otherwise, return the string 1
Date and time functions
Get date 、 Time

SELECT CURDATE(),CURRENT_DATE(),CURTIME(),NOW(),SYSDATE(),
UTC_DATE(),UTC_TIME()
FROM DUAL;

SELECT CURDATE(),CURDATE() + 0,CURTIME() + 0,NOW() + 0
FROM DUAL;

Date and time stamp conversion

SELECT UNIX_TIMESTAMP(),UNIX_TIMESTAMP('2021-10-01 12:12:32'),
FROM_UNIXTIME(1635173853),FROM_UNIXTIME(1633061552)
FROM DUAL;

Get month 、 week 、 Weeks 、 Functions such as days

SELECT YEAR(CURDATE()),MONTH(CURDATE()),DAY(CURDATE()),
HOUR(CURTIME()),MINUTE(NOW()),SECOND(SYSDATE())
FROM DUAL;

SELECT MONTHNAME('2021-10-26'),DAYNAME('2021-10-26'),WEEKDAY('2021-10-26'),
QUARTER(CURDATE()),WEEK(CURDATE()),DAYOFYEAR(NOW()),
DAYOFMONTH(NOW()),DAYOFWEEK(NOW())
FROM DUAL;


Operation function of date

type The value and meaning of :
SELECT EXTRACT(SECOND FROM NOW()),EXTRACT(DAY FROM NOW()),
EXTRACT(HOUR_MINUTE FROM NOW()),EXTRACT(QUARTER FROM '2021-05-12')
FROM DUAL;

Time and second conversion function

SELECT TIME_TO_SEC(CURTIME()),
SEC_TO_TIME(83355)
FROM DUAL;

A function that calculates the date and time

type The value of :
SELECT NOW(),DATE_ADD(NOW(),INTERVAL 1 YEAR),
DATE_ADD(NOW(),INTERVAL -1 YEAR),
DATE_SUB(NOW(),INTERVAL 1 YEAR)
FROM DUAL;
DATE_ADD(NOW(),INTERVAL 1 YEAR), Add... At the current time 1 year ,DATE_ADD(NOW(),INTERVAL -1 YEAR) amount to DATE_SUB(NOW(),INTERVAL 1 YEAR) Both are subtracted at the current time 1 year 
SELECT DATE_ADD(NOW(), INTERVAL 1 DAY) AS col1,DATE_ADD('2021-10-21 23:32:12',INTERVAL 1 SECOND) AS col2,
ADDDATE('2021-10-21 23:32:12',INTERVAL 1 SECOND) AS col3,
DATE_ADD('2021-10-21 23:32:12',INTERVAL '1_1' MINUTE_SECOND) AS col4,
DATE_ADD(NOW(), INTERVAL -1 YEAR) AS col5, # It could be negative
DATE_ADD(NOW(), INTERVAL '1_1' YEAR_MONTH) AS col6 # Need single quotes
FROM DUAL;
DATE_ADD('2021-10-21 23:32:12',INTERVAL '1_1' MINUTE_SECOND) stay 2021-10-21 23:32:12 To add 1 branch 1 second , Be careful '1_1' Not numerical , Use '' Lead up 

SELECT ADDTIME(NOW(),20),SUBTIME(NOW(),30),SUBTIME(NOW(),'1:1:3'),DATEDIFF(NOW(),'2021-10-01'),
TIMEDIFF(NOW(),'2021-10-25 22:10:10'),FROM_DAYS(366),TO_DAYS('0000-12-25'),
LAST_DAY(NOW()),MAKEDATE(YEAR(NOW()),32),MAKETIME(10,21,23),PERIOD_ADD(20200101010101,10)
FROM DUAL;
SUBTIME(NOW(),'1:1:3') Subtract... From the current time 1 Hours 1 minute 1 second 

Formatting and parsing of dates

Above Not GET_FORMAT function in fmt Common format characters and descriptions of parameters are as follows :
GET_FORMAT function in date_type and format_type The parameter values are as follows :

format : date —> character string
analysis : character string ----> date
At this point, we are talking about the explicit formatting and parsing of dates , Before , We've been exposed to implicit formatting or parsing
SELECT *
FROM employees
WHERE hire_date = '1993-01-13';
Here '1993-01-13' It's a string , Because it satisfies Date Format , So when searching , The bottom layer will automatically convert this string to Date Format , This is implicit formatting or parsing
# format :
SELECT DATE_FORMAT(CURDATE(),'%Y-%M-%D'),
DATE_FORMAT(NOW(),'%Y-%m-%d'),TIME_FORMAT(CURTIME(),'%h:%i:%S'),
DATE_FORMAT(NOW(),'%Y-%M-%D %h:%i:%S %W %w %T %r')
FROM DUAL;

# analysis : The reverse of formatting
SELECT STR_TO_DATE('2021-October-25th 11:37:30 Monday 1','%Y-%M-%D %h:%i:%S %W %w')
FROM DUAL;

SELECT GET_FORMAT(DATE,'USA')
FROM DUAL;

SELECT DATE_FORMAT(CURDATE(),GET_FORMAT(DATE,'USA'))
FROM DUAL;

Process control functions
Process processing functions can be based on different conditions , Perform different processes , Can be in SQL Statement to implement different conditional choices .MySQL The process processing functions in mainly include IF()、IFNULL() and CASE() function .
#4.1 IF(VALUE,VALUE1,VALUE2)
SELECT last_name,salary,IF(salary >= 6000,' High wages ',' Low wages ') "details"
FROM employees;

SELECT last_name,commission_pct,IF(commission_pct IS NOT NULL,commission_pct,0) "details",
salary * 12 * (1 + IF(commission_pct IS NOT NULL,commission_pct,0)) "annual_sal"
FROM employees;

#4.2 IFNULL(VALUE1,VALUE2): As a IF(VALUE,VALUE1,VALUE2) In special circumstances
SELECT last_name,commission_pct,IFNULL(commission_pct,0) "details"
FROM employees;

#4.3 CASE WHEN ... THEN ...WHEN ... THEN ... ELSE ... END
# Be similar to java Of if ... else if ... else if ... else
SELECT last_name,salary,CASE WHEN salary >= 15000 THEN ' Bones jing '
WHEN salary >= 10000 THEN ' potential share '
WHEN salary >= 8000 THEN ' Little loser '
ELSE ' grassroots ' END "details",department_id
FROM employees;

SELECT last_name,salary,CASE WHEN salary >= 15000 THEN ' Bones jing '
WHEN salary >= 10000 THEN ' potential share '
WHEN salary >= 8000 THEN ' Little loser '
END "details"
FROM employees;

#4.4 CASE ... WHEN ... THEN ... WHEN ... THEN ... ELSE ... END
# Be similar to java Of swich ... case...
/* practice 1 The inquiry department number is 10,20, 30 Employee information , If the department number is 10, Print their salary 1.1 times , 20 Department No , Print their salary 1.2 times , 30 Department No , Print their salary 1.3 Multiple , Other departments , Print their salary 1.4 Multiple */
SELECT employee_id,last_name,department_id,salary,CASE department_id WHEN 10 THEN salary * 1.1
WHEN 20 THEN salary * 1.2
WHEN 30 THEN salary * 1.3
ELSE salary * 1.4 END "details"
FROM employees;

/* practice 2 The inquiry department number is 10,20, 30 Employee information , If the department number is 10, Print their salary 1.1 times , 20 Department No , Print their salary 1.2 times , 30 Department No. prints its salary 1.3 Multiple */
SELECT employee_id,last_name,department_id,salary,CASE department_id WHEN 10 THEN salary * 1.1
WHEN 20 THEN salary * 1.2
WHEN 30 THEN salary * 1.3
END "details"
FROM employees
WHERE department_id IN (10,20,30);

Encryption and decryption functions
The encryption and decryption function is mainly used to encrypt and decrypt the data in the database , To prevent data from being stolen by others .
# PASSWORD() stay mysql8.0 To discard .
SELECT MD5('mysql'),SHA('mysql'),MD5(MD5('mysql'))
FROM DUAL;

MD5() and SHA() These two encryption methods are irreversible , Only plain text can be encrypted into dark text , You cannot decrypt dark text into plain text
边栏推荐
- NoSQL之Redis配置与优化
- [black apple series] m910x perfect black apple system installation tutorial – 2 making system USB disk -usb creation
- 去哪儿网(Qunar) DevOps 实践分享
- Taro--- day2--- compile and run
- 796 div.2 C. managing history thinking
- Logging log usage
- 【无标题】
- Taro--- day1--- construction project
- 无人机专用滑环定制要求是什么
- Taro---day2---编译运行
猜你喜欢

How about the market application strength of large-size conductive slip rings

Proe/creo product structure design - continuous research
Latest MySQL advanced SQL statement Encyclopedia

MySQL十种锁,一篇文章带你全解析

What are cookies and the security risks of v-htm
最新MySQL高级SQL语句大全

What is promise

JVM的内存模型简介

Matlb| optimal configuration of microgrid in distribution system based on complex network

Ten MySQL locks, one article will give you full analysis
随机推荐
Download, configuration and installation of MySQL
Understand the basic structure of wechat applet project
Redis主从复制、哨兵模式、集群的概述与搭建
Proe/creo product structure design - continuous research
How to build an e-commerce platform at low cost
SDF学习之扭曲模型
#796 Div.2 C. Manipulating History 思维
Comprehensive evaluation of free, easy-to-use and powerful open source note taking software
plot_ Model error: pydot and graphviz are not installed
如何在您的Shopify商店中添加实时聊天功能?
深入解析kubernetes controller-runtime
完全二叉树的节点个数[非O(n)求法 -> 抽象二分]
DeepMind | 通过去噪来进行分子性质预测的预训练
吸顶方案1
Lodash realizes anti shake and throttling functions and native implementation
手机股票开户安全吗,买股票在哪开户?
Cloud assisted privacy collection intersection (server assisted psi) protocol introduction: Learning
Sword finger offer 61 Shunzi in playing cards
LATEX 表格内容居左,中,右
云厂商为什么都在冲这个KPI?