MySql common functions such as mathematical functions and encryption functions bitsCN.com
MySql common functions, such as mathematical functions and encryption functions
There are many MySql functions. here we only list some common functions.
I. 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 greater than x.
EXP (x) // returns the x power of e (the base of the natural logarithm ).
FLOOR (x) // returns the largest integer less than x.
GREATEST (x1, x2,..., xn) // returns the maximum 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 x.
MOD (x, y) // returns the modulus (remainder) of x/y)
PI () // returns the pi value (circumference rate)
RAND () // returns a random value from 0 to 1. you can provide a parameter (seed) to generate a specified value for the RAND () random number generator.
ROUND (x, y) // returns the rounded y decimal value of parameter x.
SIGN (x) // returns the value of the symbol representing the number x.
SQRT (x) // returns the square root of a number.
TRUNCATE (x, y) // returns the result of truncating x to y decimal places.
II. aggregate functions (usually used in SELECT queries of group by clauses)
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 values in the specified column.
GROUP_CONCAT (col) returns the result of a combination of column values.
III. string functions
ASCII (char) returns the ASCII value of a character
BIT_LENGTH (str) returns the bit length of the string.
CONCAT (s1, s2. .., sn) concatenates s1, s2. .., and sn into a string.
CONCAT_WS (sep, s1, s2. .., sn) concatenates s1, s2. .., sn into a string, and uses the sep character interval.
INSERT (str, x, y, instr): Start from position x of String str. replace substring with string instr with length y. The result is returned.
FIND_IN_SET (str, list) analyzes the list separated by commas (,). if str is found, the position of str in the list is returned.
LCASE (str) or LOWER (str) returns the result of changing all characters in the str string to lowercase.
LEFT (str, x) returns the leftmost x characters in the str string.
LENGTH (s) returns the number of characters in the str string.
LTRIM (str) removes the leading space from the str string.
POSITION (substr, str) returns the POSITION of the substring substr that appears for the first time in the str string.
QUOTE (str) escape single quotes in str with a backslash
REPEAT (str, srchstr, rplcstr) returns the string 'str' repeated x times.
REVERSE (str) returns the result of REVERSE string str
RIGHT (str, x) returns the rightmost x characters in the str string.
RTRIM (str) returns the space at the end of the str string.
STRCMP (s1, s2) compares strings s1 and s2
TRIM (str) removes all spaces at the beginning and end of the string.
UCASE (str) or UPPER (str) returns the result of converting all characters in the str string to uppercase.
LOWER (str) returns the result of converting all str characters to lowercase letters.
IV. date and time functions
CURDATE () or CURRENT_DATE () returns the current date
CURTIME () or CURRENT_TIME () returns the current time
DATE_ADD (date, INTERVAL int keyword) returns the result of date plus the INTERVAL 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 the INTERVAL int (int must be formatted according to the keyword), such as: SELECTDATE_SUB (CURRENT_DATE, INTERVAL 6 MONTH );
DAYOFWEEK (date) returns the day (1 ~ 7)
DAYOFMONTH (date) returns the day (1 ~ 31)
DAYOFYEAR (date) returns the day (1 ~ 366)
DAYNAME (date) returns the week name of date, for example, SELECTDAYNAME (CURRENT_DATE );
FROM_UNIXTIME (ts, fmt) format the UNIX timestamp ts based on the specified fmt format
HOUR (time) returns 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, for example, SELECTMONTHNAME (CURRENT_DATE );
NOW () returns the current date and time
QUARTER (date) returns the QUARTER (1 ~ 4), such as SELECTQUARTER (CURRENT_DATE );
WEEK (date) returns the WEEK (0 ~ 53)
YEAR (date) returns the YEAR (1000 ~ 9999)
Some examples:
Obtain the current system Time: SELECTFROM_UNIXTIME (UNIX_TIMESTAMP ());
Select extract (YEAR_MONTH FROM CURRENT_DATE );
Select extract (DAY_SECOND FROM CURRENT_DATE );
Select extract (HOUR_MINUTE FROM CURRENT_DATE );
Returns the difference (number of months) between two date values: SELECTPERIOD_DIFF (200302,199802 );
Age calculation in Mysql:
SELECT DATE_FORMAT (FROM_DAYS (TO_DAYS (NOW ()-TO_DAYS (birthday), '% Y') + 0 AS ageFROM employee;
In this way, if Brithday is the year, month, and day of the future, the calculation result is 0.
The following SQL statement calculates the absolute age of an employee, that is, when Birthday is a future date, a negative value is obtained.
SELECT DATE_FORMAT (NOW (), '% Y')-DATE_FORMAT (birthday,' % Y')-(DATE_FORMAT (NOW (), '00-% m-% d ') <DATE_FORMAT (birthday, '00-% m-% d') AS agefrom employee
V. encryption functions
AES_ENCRYPT (str, key) returns the encrypted result of using the key pair string str with the Advanced Encryption Standard algorithm. the result of calling AES_ENCRYPT is a binary string stored as BLOB.
AES_DECRYPT (str, key) returns the decryption result of the string str encrypted with the key using the Advanced Encryption Standard algorithm.
DECODE (str, key) uses the key as the key to decrypt the encrypted string str
ENCRYPT (str, salt) uses the UNIXcrypt () function and uses the keyword salt (a string that uniquely identifies a password, just like a key) to ENCRYPT the String str
ENCODE (str, key) uses key as the key to encrypt the String str. the result of calling ENCODE () is a binary string, which is stored as BLOB.
Calculate the MD5 checksum of the str string using MD5 ().
PASSWORD (str) returns the encrypted version of the string str, which is irreversible and uses different algorithms than the encryption process of UNIX passwords.
SHA () calculates the SHA checksum of the str string
Example:
Select encrypt ('root', 'salt ');
Select encode ('xufeng', 'key ');
Select decode (ENCODE ('xufeng', 'key'), 'key'); # put encryption and decryption together
SELECT AES_ENCRYPT ('root', 'key ');
SELECT AES_DECRYPT (AES_ENCRYPT ('root', 'key'), 'key ');
SELECT MD5 ('200 ');
Select sha ('123 ');
VI. control flow functions
MySQL has four functions used for conditional operations. these functions can implement the SQL conditional logic and allow 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, resultN is returned; otherwise, default is returned.
CASE [test] WHEN [val1] THEN [result]... ELSE [default] END if test and valN are equal, resultN is returned; otherwise, default is returned.
IF (test, t, f) IF test is true, t is returned; otherwise, f is returned.
IFNULL (arg1, arg2) if arg1 is not empty, arg1 is returned; otherwise, arg2 is returned.
NULLIF (arg1, arg2) returns NULL if arg1 = arg2; otherwise, arg1 is returned.
The first of these functions is IFNULL (), which has two parameters and judges the first parameter. If the first parameter is not NULL, the function returns the first parameter to the caller. if the parameter is NULL, the second parameter is returned.
For example, SELECTIFNULL (1, 2), IFNULL (NULL, 10), IFNULL (4 * NULL, 'false ');
The NULLIF () function checks whether the two provided parameters are equal. if they are equal, NULL is returned. if they are not equal, the first parameter is returned.
For example: SELECTNULLIF (), NULLIF ('A', 'B'), NULLIF (2 + 3, 4 + 1 );
Like the IF () function provided by many scripting languages, MySQL's IF () function can also establish a simple conditional test, which has three parameters, the first is the expression to be judged. IF the expression is true, IF () returns the second parameter. IF the expression is false, IF () returns the third parameter.
For example, SELECTIF (1 <100, 3), IF (56>, 'true', 'false ');
The IF () function is applicable only when there are two possible results. However, in the real world, we may find that multiple branches are required in conditional testing. In this CASE, MySQL provides the case function, which is the same as the switch-CASE condition routine in PHP and Perl.
The format of the CASE function is a bit complex, usually as follows:
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 judged, followed by a series of WHEN-THEN blocks. The first parameter of each block specifies the value to be compared. if it is true, returns the result. All WHEN-THEN blocks END with the ELSE block. WHEN the END ends with all external CASE blocks, if each of the preceding blocks does not match, the default result specified by the ELSE block is returned. If no ELSE block is specified and all WHEN-THEN comparisons are not true, MySQL returns NULL.
There is another syntax for the CASE function, 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 test is true.
Example:
Mysql> select case 'green'
WHEN 'red' THEN 'stop'
WHEN 'Green' THEN 'go' END;
SELECTCASE 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', 'inactivated') as result from UserLoginInfo;
SELECT fname, lname, (math + sci + benchmark) AS total,
Case when (math + sci + timeout) <50 THEN 'D'
WHEN (math + sci + benchmark) BETWEEN 50 AND 150 THEN 'C'
WHEN (math + sci + benchmark) BETWEEN 151 AND 250 THEN 'B'
ELSE 'A' END
AS grade FROM marks;
SELECTIF (ENCRYPT ('Sue ', 'ts') = upass, 'allow', 'deny') AS LoginResult FROM users WHEREuname = 'Sue'; # one login verification
VII. formatting functions
DATE_FORMAT (date, fmt) format the date value according to the string fmt
FORMAT (x, y) FORMAT x as a sequence of numbers separated by commas (,). y indicates the decimal places of the result.
INET_ATON (ip) returns the number of ip addresses
INET_NTOA (num) returns the IP address represented by the number
TIME_FORMAT (time, fmt) format the time value according to the string fmt
The simplest is the FORMAT () function, which can FORMAT a large value into a comma-separated readable sequence.
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 ');
SELECT INET_NTOA (175790383 );
VIII. type conversion functions
To convert data types, MySQL provides the CAST () function, which can convert a value to a specified data type. Types: 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 );
9. system information functions
DATABASE () returns the current DATABASE name
BENCHMARK (count, expr) repeatedly runs count times for the expression expr
CONNECTION_ID () returns the connection ID of the current customer.
FOUND_ROWS () returns the total number of rows retrieved by the last SELECT query.
USER () or SYSTEM_USER () returns the current login USER name
VERSION () returns the MySQL server VERSION.
Example:
Select database (), VERSION (), USER ();
Select benchmark (9999999, LOG (RAND () * PI (); # In this example, MySQL calculates the LOG (RAND () * PI () expression 9999999 times.
BitsCN.com