MySQL common functions

Original address: https://blog.csdn.net/sugang_ximi/article/details/6664748


1. Mathematical functions

ABS(x) returns the absolute value of x
BIN(x) returns the binary value of x (OCT returns octal, HEX returns hexadecimal)
CEILING(x) returns the smallest integer value greater than x
EXP(x) returns the value e (base of natural logarithm) raised to the x power
FLOOR (x) returns the largest integer value less than x
GREATEST(x1,x2,...,xn) returns the largest value in the set
LEAST(x1,x2,...,xn) returns the smallest value in the set
LN(x) Returns the natural logarithm of
x LOG(x,y) returns the base y logarithm of
xMOD(x,y) Returns the modulo (remainder) of x/y
PI() returns the value of pi (pi)
RAND() Returns a random value between 0 and 1. You can make the RAND() random number generator generate a specified value by providing a parameter (seed).
ROUND(x,y) returns the rounded value of the argument x with y decimal places
SIGN(x) returns the value representing the sign of the number x
SQRT(x) returns the square root of a number
TRUNCATE(x,y) returns the number x truncated It is the result of y decimal places.

2.
Aggregate function (commonly used in the SELECT query of the GROUP BY clause) AVG(col) returns the average value of the specified column
COUNT(col) returns the number of non-NULL values ​​in the specified column
MIN(col) returns The minimum value of the specified column
MAX(col) returns the maximum value of the specified column
SUM(col) returns the sum of all the values ​​of the specified column
GROUP_CONCAT(col) returns the result of the combination of the column values ​​belonging to a group

3.
string function ASCII(char) returns the ASCII code value of the character
BIT_LENGTH(str) returns Bit length of the string
CONCAT(s1,s2...,sn)Concatenates s1,s2...,sn into a string
CONCAT_WS(sep,s1,s2...,sn)Concatenates s1,s2..., sn is concatenated into a string, and
INSERT(str,x,y,instr) is used to separate the characters of sep. The string str starts from the xth position, and the y-character long substring is replaced by the string instr, and the result is returned
FIND_IN_SET(str,list ) Analyze the comma-separated list list, and if str is found, return the position of str in the list
LCASE(str) or LOWER(str) Return the result of changing all characters in the string str to lowercase
LEFT(str,x) returns the character The leftmost x characters
in the string str LENGTH(s) returns the number of characters in the string str
LTRIM(str) cuts off leading spaces from the string str
POSITION(substr,str) returns the substring substr in the string str The position of the first occurrence
QUOTE(str) Escape the single quote in str with a backslash
REPEAT(str,srchstr,rplcstr) Returns the result of repeating the string str x times
REVERSE(str) Returns the result of reversing the string str
RIGHT(str,x) returns the rightmost x characters in the string str
RTRIM(str) returns the space at the end of the string str
STRCMP(s1,s2) compares the strings s1 and s2
TRIM(str) removes the head and tail of the string All spaces of
UCASE(str) or UPPER(str) Return the result of converting all characters in the string str to uppercase

4.
Date and time functions CURDATE() or CURRENT_DATE() Return the current date
CURTIME() or CURRENT_TIME() Returns the current time
DATE_ADD(date, INTERVAL int keyword) returns the result of date plus interval time int (int must be formatted according to the keyword), such as: SELECTDATE_ADD(CURRENT_DATE, INTERVAL 6 MONTH);
DATE_FORMAT(date, fmt) Format the date value according to the specified fmt format
DATE_SUB(date, INTERVAL int keyword) returns the result of date plus interval time int (int must be formatted according to the keyword), such as: SELECTDATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
DAYOFWEEK(date) Returns the day of the week represented by date (1~7)
DAYOFMONTH(date) Returns the day of the month where date is (1~31)
DAYOFYEAR(date) Returns the day of the year where date is days (1~366)
DAYNAME(date) returns the week name of the date, such as: SELECT DAYNAME(CURRENT_DATE);
FROM_UNIXTIME(ts,fmt) According to the specified fmt format, format the UNIX timestamp ts
HOUR(time) Return the hour value of time (0~23)
MINUTE(time) returns the minute value of time (0~59)
MONTH(date) returns the month value of date (1~12)
MONTHNAME(date) returns the month name of date, such as: SELECT MONTHNAME(CURRENT_DATE);
NOW() returns The current date and time
QUARTER(date) returns the quarter (1~4) of the year in the date, such as SELECT QUARTER(CURRENT_DATE);
WEEK(date) returns the date as the week of the year (0~53)
YEAR (date) returns the year (1000~9999) of the date date
Some examples:
Get the current system time: SELECT FROM_UNIXTIME(UNIX_TIMESTAMP());
SELECT EXTRACT(YEAR_MONTH FROM CURRENT_DATE);
SELECT EXTRACT(DAY_SECOND FROM CURRENT_DATE);
SELECT EXTRACT(HOUR_MINUTE FROM CURRENT_DATE);
Return the difference (months) between two date values: SELECT PERIOD_DIFF(200302,199802);
Calculate age in Mysql:
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birthday)),'%Y ')+0 AS age FROM employee;
This way, if Britain is a future year, month, day, the result is 0.
The following SQL statement calculates the absolute age of the employee, i.e. when the Birthday is a future date, it will get a negative value.
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birthday, '%Y') -(DATE_FORMAT(NOW(), '00-%m-%d') <DATE_FORMAT(birthday, '00-%m -%d')) AS age from employee

5. The encryption function
AES_ENCRYPT(str,key) returns the result of encrypting the string str using the Advanced Encryption Standard algorithm with the key key. The result of calling AES_ENCRYPT is a binary string with BLOB type storage
AES_DECRYPT(str,key) Return the result of decrypting the string str with the key key using the Advanced Encryption Standard algorithm
DECODE(str,key) Use the key as the key to decrypt the encrypted string str
ENCRYPT(str,salt) Use UNIXcrypt() function, encrypts the string str with the keyword salt (a string that can uniquely determine the password, like a key)
ENCODE(str,key) Use key as the key to encrypt the string str, the result of calling ENCODE() is a binary string, which is stored in BLOB type
MD5() Calculate the MD5 checksum of the string str
PASSWORD(str) returns The encrypted version of the string str. This encryption process is irreversible and uses a different algorithm than the UNIX password encryption process.
SHA() Calculates the Secure Hash Algorithm (SHA) checksum of the string str
Example :
SELECT ENCRYPT('root','salt');
SELECT ENCODE('xufeng','key');
SELECT DECODE(ENCODE(' xufeng','key'),'key');#encryption and decryption put together
SELECT AES_ENCRYPT('root','key');
SELECT AES_DECRYPT(AES_ENCRYPT('root','key'),'key');
SELECT MD5('123456');
SELECT SHA('123456');

6. Control flow functions
MySQL has four functions for conditional operations. These functions can implement the conditional logic of SQL, allowing developers to convert some application business logic to the database background.
MySQL control flow functions:
CASE WHEN[test1] THEN [result1]...ELSE [default] END If testN is true, return resultN, otherwise return default
CASE [test] WHEN[val1] THEN [result]...ELSE [default]END If test and valN are equal, return resultN, otherwise return default
IF(test,t,f) If test is true, return t; otherwise Return f
IFNULL(arg1,arg2) If arg1 is not empty, return arg1, otherwise return arg2
NULLIF(arg1,arg2) If arg1=arg2 return NULL; otherwise return arg1
The first of these functions is IFNULL(), which has two parameters, and the first parameter is judged. If the first parameter is not NULL, the function will return the first parameter to the caller; if it is NULL, it will return the second parameter.
Such as: SELECT IFNULL(1,2), IFNULL(NULL,10), IFNULL(4*NULL,'false');
The NULLIF() function will check whether the provided two parameters are equal, if they are equal, return NULL, If not equal, return the first argument.
Such as: SELECT NULLIF(1,1), NULLIF('A', 'B'), NULLIF(2+3,4+1);
Like the IF() function provided by many scripting languages, MySQL's IF() function A simple conditional test can also be created. This function has three parameters. The first is the expression to be evaluated. If the expression is true, IF() will return the second parameter. If it is false, IF() will return the third parameter.
Such as: SELECTIF(1<10,2,3),IF(56>100,'true','false');
The IF() function is suitable for use when there are only two possible outcomes. However, in the real world, we may find that multiple branches are required in conditional tests. In this case, MySQL provides the CASE function, which is the same as the switch-case conditional routine in PHP and Perl.
The format of the CASE function is somewhat complicated and usually looks like this:
CASE [expression to be evaluated]
WHEN [val 1] THEN [result 1]
WHEN [val 2] THEN [result 2]
WHEN [val 3] THEN [result 3]
. .....
WHEN [val n] THEN [result n]
ELSE [default result]
END
Here, the first parameter is the value or expression to be evaluated, followed by a series of WHEN-THEN blocks, each The first parameter of a block specifies the value to compare, and if true, returns the result. All WHEN-THEN blocks will end with an ELSE block. When END ends all outer CASE blocks, the default result specified by the ELSE block will be returned if each preceding block does not match. If no ELSE block is specified, and all WHEN-THEN comparisons are not true, MySQL will return NULL.
The CASE function has another syntax, which is sometimes very convenient to use, as follows:
CASE
WHEN [conditional test 1] THEN [result 1]
WHEN [conditional test 2] THEN [result 2]
ELSE [default result]
END
In this condition, the returned result depends on whether the corresponding conditional test is true.
Example:
mysql>SELECT CASE 'green'
     WHEN 'red' THEN 'stop'
     WHEN 'green' THEN 'go' END;
SELECT CASE 9 WHEN 1 THEN 'a' WHEN 2 THEN 'b' ELSE 'N/A' END;
SELECT CASE WHEN (2+2)=4 THEN 'OK' WHEN(2+2)<>4 THEN 'not OK' END ASSTATUS;
SELECT Name,IF((IsActive = 1),'Activated','Inactive ') AS RESULT FROMUserLoginInfo;
SELECT fname,lname,(math+sci+lit) AS total,
CASE WHEN (math+sci+lit) < 50 THEN 'D'
WHEN (math+sci+lit) BETWEEN 50 AND 150 THEN ' C'
WHEN (math+sci+lit) BETWEEN 151 AND 250 THEN 'B'


SELECT IF(ENCRYPT('sue','ts')=upass,'allow','deny') AS LoginResultFROM users WHERE uname = 'sue';#A login verification

7.
Formatting function DATE_FORMAT(date,fmt) according to String fmt format date date value
FORMAT(x,y) Format x as a comma-separated sequence of numbers, y is the number of decimal places of the result
INET_ATON(ip) Returns the numeric representation of the IP address INET_NTOA
(num) Returns the number The IP address represented by
TIME_FORMAT(time,fmt) Formats the time value according to the string fmt
. The simplest of these is the FORMAT() function, which formats large values ​​into readable sequences separated by commas.
Example:
SELECT FORMAT(34234.34323432,3);
SELECT DATE_FORMAT(NOW(),'%W,%D %M %Y %r');
SELECT DATE_FORMAT(NOW(),'%Y-%m-%d') ;
SELECT DATE_FORMAT(19990330,'%Y-%m-%d');
SELECT DATE_FORMAT(NOW(),'%h:%i %p');
SELECT INET_ATON('10.122.89.47');



For data type conversion, MySQL provides the CAST() function, which can convert a value to a specified data type. Types are: BINARY,CHAR,DATE,TIME,DATETIME,SIGNED,UNSIGNED
Example:
SELECT CAST(NOW() AS SIGNED INTEGER),CURDATE()+0;
SELECT 'f'=BINARY 'F','f'=CAST ('F' AS BINARY);

Nine, the system information function
DATABASE() returns the current database name
BENCHMARK(count,expr) Repeats the expression expr count times
CONNECTION_ID() Returns the connection ID of the current customer
FOUND_ROWS() Returns the last SELECT Query the total number of rows retrieved by
USER() or SYSTEM_USER() Return the current login user name
VERSION() Return the version of the MySQL server
Example :
SELECT DATABASE(),VERSION(),USER();
SELECTBENCHMARK(9999999,LOG(RAND() *PI()));#In this example, MySQL evaluates the LOG(RAND()*PI()) expression 9999999 times.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324848018&siteId=291194637