MySQL common function 1

Source: Internet
Author: User
Tags mathematical functions natural logarithm
MySQL common functions: ABS (x )??????????????????? Returns the BIN (x) of the absolute value of x to the binary value of x (OCT returns octal, HEX returns hexadecimal) CEILING (x )??????????????? Returns the x power FLOOR (x) of the minimum integer EXP (x) value greater than x returned by e (base of the natural logarithm). returns the largest integer less than x.

MySQL common functions 1. mathematical functions ABS (x )??????????????????? Returns the BIN (x) of the absolute value of x to the binary value of x (OCT returns octal, HEX returns hexadecimal) CEILING (x )??????????????? Returns the x power FLOOR (x) of the minimum integer EXP (x) value greater than x returned by e (base of the natural logarithm). returns the largest integer less than x.

MySQL common functions 1
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 value 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 between 0 and 1. You can provide a parameter (SEED) to generate a specified value for 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 in a group? 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 into uppercase 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: SELECT DATE_ADD (CURRENT_DATE, INTERVAL 6 MONTH );
DATE_FORMAT (date, fmt )?? Format the date value in 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: SELECT DATE_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, select dayname (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, select monthname (CURRENT_DATE );
NOW ()???? Returns the current date and time.
QUARTER (date )??? Returns the quarter (1 ~ 4), such as select quarter (CURRENT_DATE );
WEEK (date )??? Returns the week number Of The Year (0 ~ 53)
YEAR (date )??? Returns the year of the date (1000 ~ 9999) Examples:
Obtain 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 );
Returns the difference between two date values (number of months): SELECT PERIOD_DIFF (200302,199802 );
Age calculation in Mysql:
SELECT DATE_FORMAT (FROM_DAYS (TO_DAYS (NOW ()-TO_DAYS (birthday), '% y') + 0 AS age FROM 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 age from employee? V. encryption functions
AES_ENCRYPT (str, key )?? Returns the encrypted result of using the Advanced Encryption Standard algorithm to encrypt the string str with the key. The result of calling AES_ENCRYPT is a binary string, which is stored as BLOB.
AES_DECRYPT (str, key )?? Returns the decryption result of the string str encrypted with the key.
DECODE (str, key )??? Use key as the key to decrypt the encrypted string str
ENCRYPT (str, salt )?? Use the UNIX crypt () function and the keyword salt (a string that uniquely identifies the password, just like the key) to encrypt the string str
ENCODE (str, key )??? The key is used as the key to encrypt the str string. The result of calling ENCODE () is a binary string, which is stored as BLOB.
MD5 ()???? Calculate the MD5 checksum of the str string.
PASSWORD (str )??? Returns the encrypted version of the string 'str'. This encryption process is irreversible and uses different algorithms than the UNIX password encryption process.
SHA ()???? Calculate the SHA checksum of the str string:
Select encrypt ('root', 'salt'); select encode ('xufeng', 'key'); select decode (ENCODE ('xufeng', 'key '), 'key'); # SELECT AES_ENCRYPT ('root', 'key'); SELECT AES_DECRYPT (AES_ENCRYPT ('root', 'key '), 'key'); SELECT MD5 ('20140901'); select sha ('20160901 ');
? 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, the first function that returns arg1 is IFNULL (). It 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, select ifnull (), IFNULL (NULL, 10), IFNULL (4 * NULL, 'false'); The NULLIF () function checks whether the two parameters are equal, if they are equal, NULL is returned. If they are not equal, the first parameter is returned.
For example: select nullif (), 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. This function has three parameters. The first is the expression to be judged. IF the expression is true, IF () the second parameter is returned. IF it is false, IF () will return the third parameter.
For example: select if (1 <100, 3), IF (56>, 'true', 'false'); IF () functions are suitable for use 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
In this case, 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; 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 AS STATUS; SELECT Name, IF (IsActive = 1), 'activated ', 'inactivity') as result from UserLoginInfo; SELECT fname, lname, (math + sci + timeout) 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 'endas grade FROM marks; SELECT IF (ENCRYPT ('sue ', 'ts') = upass, 'allow ', 'Deny') AS LoginResult FROM users WHERE uname = 'sue '; # One login verification
? VII. Formatting Functions
DATE_FORMAT (date, fmt )?? Format the date value based on the string fmt
FORMAT (x, y )??? Format x as a numerical sequence separated by commas (,). y indicates the number of decimal places in the result.
INET_ATON (ip )??? Returns the number of IP addresses.
INET_NTOA (num )??? Returns the IP address represented by a 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 name of the current database.
BENCHMARK (count, expr )?? Repeat the expression expr for count times
CONNECTION_ID ()??? Returns the connection ID of the current customer.
FOUND_ROWS ()??? Returns the total number of rows retrieved from 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.
? Source: http://bxbx258.blog.51cto.com/339450/106008

?

?

?

?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.