Databases often use functions

Source: Internet
Author: User
Tags mathematical functions month name natural logarithm rand square root value of pi

?? One, the string function
ASCII (char) returns the ASCII code value of a character
Bit_length (str) returns the bit length of a string
CONCAT (S1,S2...,SN) to concatenate s1,s2...,sn into a string
Concat_ws (SEP,S1,S2...,SN) joins the S1,S2...,SN as a string. and use the Sep character interval
INSERT (STR,X,Y,INSTR) starts the string str from position x. A substring of y characters is replaced with a string InStr, which returns the result
Find_in_set (str,list) parses a comma-separated list of lists. Suppose Str is found and returns the position of STR in the list
LCASE (str) or lower (str) Returns the result of changing all characters in the string str to lowercase
Left (str,x) returns the leftmost X character in a string str
LENGTH (s) returns the number of characters in the string str
LTRIM (str) cuts the opening space from the string str
POSITION (SUBSTR,STR) returns the position of the substring substr the first occurrence in the string str
QUOTE (str) escapes single-cited in Str with a backslash
REPEAT (STR,SRCHSTR,RPLCSTR) Returns the result of a string str repeated x times
REVERSE (str) Returns the result of reversing the string str
Right (STR,X) returns the rightmost X character in a string str
RTRIM (str) returns a space at the trailing end of a string str
STRCMP (S1,S2) comparison strings S1 and S2
TRIM (str) removes all whitespace from string header and trailing
UCASE (str) or upper (str) returns the result of converting all characters in the string str to uppercase

Second, aggregation function (often used in the GROUP BY clause in the SELECT query)
Avg (COL) returns the average 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 a combination of column value connections belonging to a group

Three, mathematical functions

ABS (x) returns the absolute value of X
BIN (x) returns the binary of X (Oct returns octal.) Hex returns HEX)
CEILING (x) returns the smallest integer value greater than X
EXP (x) return value E (base of natural logarithm) x Times Square
Floor (x) returns the maximum integer value less than x
Greatest (x1,x2,..., xn) returns the largest value in the collection
LEAST (x1,x2,..., xn) returns the smallest value in the collection
LN (x) returns the natural logarithm of X
Log (x, y) returns the X-base logarithm
MOD (x, y) returns the modulo (remainder) of x/y
Pi () returns the value of Pi (pi)
RAND () returns a random value from 0 to 1, enabling the rand () random number generator to generate a specified value by providing a number of parameters (seed).
ROUND (x, y) returns the rounding of the parameter x with a Y-decimal value
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 a number x truncated to Y decimal places


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 date plus the result of the interval int (int must be formatted according to the keyword), such as: Selectdate_add (Current_date,interval 6 MONTH);
Date_format (DATE,FMT) formats date values in the specified FMT format
date_sub (date,interval int keyword) returns the date plus the result of 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 ordinal of the week represented by date (1~7)
DayOfMonth (date) Return date is the day of the one month (1~31)
DayOfYear (date) returns the day ordinal of a year (1~366)
Dayname (date) returns the weekday name of date, such as SELECT dayname (current_date);
From_unixtime (TS,FMT) formats UNIX timestamp TS According to the specified FMT format
HOUR (time) returns the hour value (0~23)
MINUTE (time) returns the minute value of time (0~59)
Month (date) returns the months 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 a date in the quarter of the year (1~4). such as Select QUARTER (current_date);
WEEK (date) Returns a date of the week ordinal of a year (0~53)
Year (date) returns the date of day (1000~9999)
Some demo examples:
Get 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 (number of months) between two date values: SELECT Period_diff (200302,199802);
Calculate the age in MySQL:
SELECT Date_format (From_days (To_days (now ())-to_days (birthday)), '%Y ') +0 as-from employee;
So, suppose Brithday is the future of the month and the day. The result of the calculation is 0.


The following SQL statement calculates the absolute age of an employee. That is, when the birthday is a future date, a negative value will be 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

Five, encryption function
Aes_encrypt (Str,key) Returns the result of encrypting the string str with the key key using the Advanced Encryption Standard algorithm. The result of calling Aes_encrypt is a binary string, stored as a BLOB type
Aes_decrypt (Str,key) Returns the result of decrypting the string str with the key key using the Advanced Encryption Standard algorithm
DECODE (Str,key) uses key as key to decrypt encrypted string str
ENCRYPT (Str,salt) uses the Unixcrypt () function, using the keyword salt (a string that uniquely determines the password, 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 a BLOB type
MD5 () computes the MD5 checksum of the string str
PASSWORD (str) returns the encrypted version number of the string str, which is irreversible, and the Unixpassword encryption process uses a different algorithm.


SHA () computes the Secure Hash Algorithm (SHA) checksum of the string str
Demo Sample:
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 (' 123456 ');
SELECT SHA (' 123456 ');

VI. Control Flow function
MySQL has 4 functions that are used to perform conditional operations that implement the conditional logic of SQL. Agree that the developer translates some application business logic into the database backend.
MySQL Control flow function:
Case When[test1] then [RESULT1] ... ELSE [Default] end assumes that TESTN is true. Returns the RESULTN, otherwise returns the default
case [Test] when[val1) Then [result] ... else [Default]end assumes that test and VALN are equal, returns RESULTN, otherwise returns the default
if (test,t,f) assumes that test is true, return T. Otherwise, return F
Ifnull (ARG1,ARG2) assumes arg1 is not empty, returns ARG1, otherwise returns ARG2
Nullif (ARG1,ARG2) assumes that arg1=arg2 returns NULL, otherwise returns ARG1
The first of these functions is ifnull (), which has two parameters and infers the first one. Assuming that the first parameter is not NULL, the function returns the first number of parameters to the caller. Assuming null, a second parameter is returned.


such as: SELECT Ifnull, Ifnull (null,10), ifnull (4*null, ' false ');
The Nullif () function will verify that the supplied two parameters are equal, assuming equality, return NULL, assuming unequal, and return the first parameter.
such as: 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 create a simple conditional test. This function has three parameters. The first is an expression to be inferred. Assuming the expression is true, if () will return the second parameter, assuming false, if () will return a third parameter.
such as: Selectif (1<10,2,3), if (56>100, ' true ', ' false ');
The IF () function is suitable for use only if there are only two possible outcomes. However, in the real world. We may have multiple branches in the current condition test.

In such a case. MySQL provides the case function, which is the same as the switch-case conditional routine for PHP and the Perl language.


The format of the case function is somewhat complex, usually as seen in the following:
case [expression to being 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 inferred. Next is a series of when-then blocks, with the first parameter of each block specifying a value to be compared, assuming true. The result is returned.

All When-then blocks will end with the else block. When end ends all external case blocks, the default result specified by the else block is returned if each of the preceding blocks does not match. Suppose you do not specify an else block. And all the when-then are not true, MySQL will return null.
The case function also has a second syntax, which is sometimes convenient to use, such as the following:
Case
When [conditional test 1] Then [result 1]
When [conditional test 2] Then [result 2]
ELSE [Default result]
END
In such a condition, the result of the return depends on whether the test is true or not.
Demo Sample:
Mysql>select case ' green '
When the ' red ' then ' stop '
When the ' green ' then ' go ' END;
SELECT Case 9 If 1 then ' a ' is 2 Then ' B ' ELSE ' n/a ' END;
SELECT case When (=4) "OK" when (+/-) <>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) < ' D '
When (Math+sci+lit) between and "C"
When (Math+sci+lit) between 151 and "B"
ELSE ' A ' END
As grade from Marks;
SELECT IF (ENCRYPT (' Sue ', ' ts ') =upass, ' Allow ', ' deny ') as Loginresultfrom users WHERE uname = ' Sue '; #一个登陆验证

Vii. formatting functions
Date_format (DATE,FMT) formatted date value by string FMT
Format (x, y) formats x as a comma-separated sequence of numbers, and Y is the number of decimal digits of the result
Inet_aton (IP) Returns the number representation of an IP address
Inet_ntoa (num) returns the IP address represented by the number
Time_format (TIME,FMT) format time value by string FMT
The simplest of these is the format () function, which is capable of formatting large numeric values into an easy-to-read sequence with a comma interval.
Demo Sample:
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 function
For data type conversions. MySQL provides the cast () function, which converts a value to the specified data type. Types are: binary,char,date,time,datetime,signed,unsigned
Demo Sample:
SELECT CAST (now () as signed INTEGER), Curdate () +0;
SELECT ' F ' =binary ' f ', ' F ' =cast (' F ' as BINARY);

Nine, System Information function
Database () returns the current DB name
BENCHMARK (count,expr) Executes the expression expr repeatedly count times
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 username
Version () returns the revision number of the MySQLServer
Demo Sample:
SELECT DATABASE (), VERSION (), USER ();
Selectbenchmark (9999999,log (rand () *pi ())), #该例中, MySQL calculates the LOG (rand () *pi ()) expression 9,999,999 times.


Databases often use functions

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.