MYSQL entry 7: MYSQL common functions bitsCN.com
MYSQL entry 7: MYSQL common functions
Related links:
MYSQL: Basic operations
Http: // database/201212/173868 .html
MYSQL 2: use regular expressions to search
Http: // database/201212/173869 .html
MYSQL 3: full text search
Http: // database/201212/173873 .html
MYSQL entry 4: MYSQL data types
Http: // database/201212/175536 .html
MYSQL entry 5: MYSQL character set
Http: // database/201212/175541 .html
MYSQL getting started 6: MYSQL operators
Http: // database/201212/175862 .html
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)
LN (x) returns the natural logarithm of x.
LOG (x, y) returns the base y logarithm of x.
MOD (x, y) returns the modulo (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.
Example:
Mysql> select abs (-1 );
+ --------- +
| Abs (-1) |
+ --------- +
| 1 |
+ --------- +
Mysql> select ceiling (5.2 );
+ -------------- +
| Ceiling (5.2) |
+ -------------- +
| 6 |
+ -------------- +
Mysql> select mod (10, 4 );
+ ----------- +
| Mod (10, 4) |
+ ----------- +
| 2 |
+ ----------- +
Mysql> select rand ();
+ ------------------ +
| Rand () |
+ ------------------ +
| 1, 0.98648901096218 |
+ ------------------ +
Mysql> select truncate (5.1235, 2 );
+ -------------------- +
| Truncate (5.1235, 2) |
+ -------------------- +
| 1, 5.12 |
+ -------------------- +
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
REPLACE (str, from_str, to_str) returns the str string. all occurrences of the from_str string are replaced by the to_str string.
REPEAT (str, x) returns the result of str REPEAT 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.
Example:
Mysql> select bit_length ('ABC ');
+ -------------------- +
| Bit_length ('ABCD') |
+ -------------------- +
| 32 |
+ -------------------- +
Mysql> select insert ('abcdef', 2, 3, 'ghilj ');
+ ------------------------------ +
| Insert ('abcdef', 2, 3, 'ghilj') |
+ ------------------------------ +
| Aghiljef |
+ ------------------------------ +
Mysql> select right ('abcdef', 3 );
+ ------------------- +
| Right ('abcdef', 3) |
+ ------------------- +
| Def |
+ ------------------- +
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 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: 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_DAYS (N) returns a day N and a DATE value. (Starting from)
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 (0 ~ 53)
YEAR (date) returns the YEAR (1000 ~ 9999)
Example:
Mysql> select from_unixtime (unix_timestamp ());
+ --------------------------------- +
| From_unixtime (unix_timestamp () |
+ --------------------------------- +
| 23:11:24 |
+ --------------------------------- +
Mysql> select extract (year_month from current_date );
+ --------------------------------------- +
| Extract (year_month from current_date) |
+ --------------------------------------- +
| 1, 201212 |
+ --------------------------------------- +
Mysql> select week (current_date ());
+ ---------------------- +
| Week (current_date () |
+ ---------------------- +
| 50 |
+ ---------------------- +
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 UNIX crypt () 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:
Mysql> select md5 ('20140901 ');
+ ---------------------------------- +
| Md5 ('20140901') |
+ ---------------------------------- +
| E10adc3949ba59abbe56e057f20f883e |
+ ---------------------------------- +
Mysql> select password ('123 ');
+ ------------------------------------------- +
| Password ('000000') |
+ ------------------------------------------- +
| * 6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+ ------------------------------------------- +
Mysql> select sha ('20140901 ');
+ ------------------------------------------ +
| Sha ('20140901') |
+ ------------------------------------------ +
| 7c4a8d09ca3762af61e59520943dc26494f8941b |
+ ------------------------------------------ +
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.
Example:
Mysql> select case 'sz 'when' sz 'Then 'Shenzhen'
-> When 'gz 'then' guangzhou'
-> When 'xm 'then' xiamen'
-> Else 'n'/A' end;
+ -----------------------------------------------------------
| Case 'sz 'when' sz 'Then 'Shenzhen'
When 'gz 'then' guangzhou'
When 'xm 'then' xiamen'
Else 'n'/A' end |
+ -----------------------------------------------------------
| Shenzhen
+ -----------------------------------------------------------
Mysql> select IF (sex = 1), 'male', 'female ');
ERROR 1054 (42S22): Unknown column 'Sex' in 'Field list'
Mysql> select IF (0 = 1), 'male', 'female ');
+ --------------------------- +
| IF (0 = 1), 'male', 'female') |
+ --------------------------- +
| Female |
+ --------------------------- +
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
Example:
Mysql> select format (1324.343633, 2 );
+ ----------------------- +
| Format (1324.343633, 2) |
+ ----------------------- +
| 1, 1,324.34 |
+ ----------------------- +
Mysql> select date_format (now (), '% Y-% m-% d ');
+ ------------------------------- +
| Date_format (now (), '% Y-% m-% d') |
+ ------------------------------- +
| 2012-12-12 |
+ ------------------------------- +
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:
Mysql> select cast (now () as signed integer );
+ ------------------------------- +
| Cast (now () as signed integer) |
+ ------------------------------- +
| 1, 20121212232553 |
+ ------------------------------- +
9. system information functions
DATABASE () returns the current DATABASE name
SCHEMA () and DATABASE () have the same meaning
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.
ROW_COUNT () returns the number of rows updated, inserted, or deleted by the preceding statement. The number of rows is the same as the number of rows displayed on the mysql client and the value returned by the mysql_affected_rows () c api function.
LAST_INSERT_ID () LAST_INSERT_ID (expr) automatically returns the first value that occurred when the last INSERT or UPDATE query is set for the AUTO_INCREMENT column
USER () or SYSTEM_USER () returns the current login USER name
SESSION_USER () and USER () have the same meaning
SYSTEM_USER () and USER () have the same meaning
CURRENT_USER, CURRENT_USER () returns the username and host name combination verified by the current session
VERSION () returns the MySQL server VERSION.
CHARSET (str) returns the character set of the string independent variable
COERCIBILITY (str) returns the full-order computation value of the string independent variable.
COLLATION (str) returns the sorting method of string parameters
Example:
Mysql> select database ();
+ ------------ +
| Database () |
+ ------------ +
| Test |
+ ------------ +
Mysql> select user ();
+ ---------------- +
| User () |
+ ---------------- +
| Root @ localhost |
+ ---------------- +
Mysql> select version ();
+ --------------------- +
| Version () |
+ --------------------- +
| 5.1.28-rc-community |
+ --------------------- +
10. Other functions
DEFAULT (col_name) returns the DEFAULT value of a table column.
UUID () returns a string that is unique in time and space.
Example:
Mysql> select uuid ();
+ -------------------------------------- +
| Uuid () |
+ -------------------------------------- +
| Ddf93e7b-4460-11e2-aaaa-fc6e2fa4a75a |
+ -------------------------------------- +
BitsCN.com