ABS function: Find the absolute value
Absolute Value Function ABS(x)
Returns the absolute value of x. The absolute value of a positive number is itself, the absolute value of a negative number is its opposite, and the absolute value of 0 is 0.
SELECT ABS(5),ABS(-2.4),ABS(-24),ABS(0);
SQRT function: find the quadratic root S
Square Root Function SQRT(x)
Returns the quadratic root of a nonnegative number x. Negative numbers do not have a square root, and the result is returned as NULL
.
SELECT SQRT(25),SQRT(120),SQRT(-9);
MOD function: find the remainder
The remainder function MOD(x,y)
returns the remainder after dividing x by y. It MOD()
also works for numbers with a fractional part. It returns the remainder after division.
SELECT MOD(63,8),MOD(120,10),MOD(15.5,3);
CEIL and CELING functions: round up
The rounding function has the same meaning CEIL(x)
as CEILING(x)
, returns the smallest integer value not less than x, and converts the return value to one BIGINT
.
SELECT CEIL(-2.5),CEILING(2.5);
FLOOR function: round down
FLOOR(x)
The function returns the largest integer value less than x.
SELECT FLOOR(5),FLOOR(5.66),FLOOR(-4),FLOOR(-4.66)
RAND function: Generate random numbers
RAND()
When the function is called, a random number between 0 and 1 can be generated.
SELECT RAND(), RAND(), RAND()
ROUND function: rounding
The ROUND(x) function returns the integer closest to the parameter x; ROUND(x,y)
the function rounds the parameter x, and the return value retains the specified y digits after the decimal point.
SELECT ROUND(-6.6),ROUND(-8.44),ROUND(3.44)
SIGN function: returns the sign of the parameter
Sign function SIGN(x)
Returns the sign of the parameter. When the value of x is negative, zero and positive, the returned result is -1, 0 and 1 in turn.
SELECT SIGN(-6),SIGN(0),SIGN(34)
POW and POWER Functions: Finding Powers
POW(x,y)
The functions and POWER(x,y)
functions are used to calculate x raised to the y power.
SELECT POW(5,-2),POW(10,3),POW(100,0),POWER(4,3),POWER(6,-3)
SIN function: find the sine value
Sine Function SIN(x)
Returns the sine of x, where x is in radians.
SELECT SIN(1),SIN(0.5*PI())
ASIN function: Find the arc sine
arcsine function ASIN(x)
Returns the arcsine of x, or NULL if x is not in the range -1 to 1.
SELECT ASIN(0.8414709848078965),ASIN(2)
COS function: Find the cosine value
Cosine Function COS(x)
Returns the cosine of x, where x is in radians.
SELECT COS(1),COS(0),COS(PI())
ACOS function: find the arc cosine value
Inverse cosine function ACOS(x)
. The value of x must be in the range -1 to 1, otherwise NULL is returned.
SELECT ACOS(2),ACOS(1),ACOS(-1)
TAN function: find the tangent value
Tangent Function TAN(x)
Returns the tangent of x, where x is the given value in radians.
SELECT TAN(1),TAN(0)
ATAN function: Find the arc tangent
arctangent ATAN(x)
Returns the arctangent of x, where tangent is the value of x.
SELECT ATAN(1.5574077246549023),ATAN(0)
COT function: Find the cotangent value
Cotangent Function COT(x)
Returns the cotangent of x, where x is the given value in radians.
SELECT COT(1)
LENGTH function: Get the length of a string
LENGTH(str)
The return value of the function is the byte length of the string. uft8
When using a variable-length character encoding (UNICODE, also known as Unicode) coded character set, a Chinese character is 3 bytes, and a number or letter is 1 byte.
SELECT LENGTH('name'),LENGTH('数据库')
CONCAT function: string concatenation
CONCAT(sl,s2,...)
The function returns a string resulting from concatenating the parameters, which may have one or more parameters.
If any parameter is NULL
, the return value is NULL
. If all arguments are nonbinary strings, the result is a nonbinary string. If the argument contains any binary string, the result is a binary string.
SELECT CONCAT('MySQL','5.7'),CONCAT('MySQL',NULL)
INSERT function: replace a string
Replace String function INSERT(s1,x,len,s2)
Returns the string s1 with the substring starting at position x and replaces s2 with a string len characters long.
If x exceeds the string length, the return value is the original string. If the length of len is greater than the length of the other strings, replacement starts at position x. If any parameter is NULL, the return value is NULL.
SELECT INSERT('Football',2,4,'Play') AS col1,
-> INSERT('Football',-1,4,'Play') AS col2,
-> INSERT('Football',3,20,'Play') AS col3;
LOWER function: Convert letters to lowercase
Alphabetic lowercase conversion function LOWER(str)
can convert all alphabetic characters in the string str into lowercase.
SELECT LOWER('BLUE'),LOWER('Blue')
UPPER function: Convert letters to uppercase
The uppercase conversion function UPPER(str)
can convert all the alphabetic characters in the string str into uppercase.
SELECT UPPER('green'),UPPER('Green')
LEFT function: intercept a string from the left
LEFT(s,n)
The function returns the leftmost n characters of the string s.
SELECT LEFT('MySQL',2)
RIGHT function: intercept the string from the right
RIGHT(s,n)
The function returns the rightmost n characters of the string s.
SELECT RIGHT('MySQL',3)
TRIM function: remove spaces
Remove Whitespace function TRIM(s)
Removes whitespace from both sides of the string s.
SELECT '[ mobile ]',CONCAT('[',TRIM(' mobile '),']')
REPLACE function: string replacement
The replace function REPLACE(s,s1,s2)
replaces all occurrences of string s1 in string s with string s2.
SELECT REPLACE('aaa.mysql.com','a','w')
STR_TO_DATE function: The function is to convert the time format string
STR_TO_DATE(str,format)
DATETIME
The function is to convert the time format string (str) into a type value according to the provided display format (format) .
SELECT STR_TO_DATE('2017-01-06 10:20:30','%Y-%m-%d %H:%i:%s') AS result;
SUBSTRING function: intercept a string
This function is equivalent to SUBSTR(s,n,len)
the get substring function SUBSTRING(s,n,len)
with the format of the len parameter, and returns a substring of the same length as len characters from the string s, starting at position n.
It is also possible to use a negative value for n. If so, the position of the substring starts at the nth character from the end of the string, that is, the last nth character, not at the beginning of the string.
SELECT SUBSTRING('computer',3) AS col1,
-> SUBSTRING('computer',3,4) AS col2,
-> SUBSTRING('computer',-3) AS col3,
-> SUBSTRING('computer',-5,3) AS col4
REVERSE function: reverse a string
String reverse function REVERSE(s)
can reverse the string s, and the sequence of the returned string is opposite to that of the string s.
SELECT REVERSE('hello')
CURDATE and CURRENT_DATE functions: Get the current date of the system
CURDATE()
Same function as CURRENT_DATE()
the function, returns the current date as a value in the format of "YYYY-MM-DD" or "YYYYMMDD", and the specific format depends on whether the function is used in a string or number context.
SELECT CURDATE(),CURRENT_DATE(),CURRENT_DATE()+0
CURTIME and CURRENT_TIME functions: get the current time of the system
CURTIME()
Same function as CURRENT_TIME()
the function, returns the current time in "HH:MM:SS" or "HHMMSS" format, the specific format depends on the function is used in a string or number context.
SELECT CURTIME(),CURRENT_TIME(),CURRENT_TIME()+0
NOW and SYSDATE functions: Get the current date and time
NOW()
The function is the same as SYSDATE()
the function, it returns the current date and time value, the format is "YYYY-MM-DD HH:MM:SS" or "YYYYMMDDHHMMSS", the specific format depends on whether the function is used in a string or number context.
SELECT NOW(),SYSDATE()
NOW()
Although both represent the current time in MySQL SYSDATE()
, NOW()
the value of is the time when the statement starts to execute, while SYSDATE()
the value of is the dynamic real-time time during the execution of the statement.
SELECT NOW(),sysdate(),sleep(3),NOW(),sysdate()
UNIX_TIMESTAMP function: get UNIX timestamp
UNIX_TIMESTAMP(date)
If called with no arguments, returns a UNIX timestamp of type unsigned integer (seconds since '1970-01-01 00:00:00' GMT).
If called with date UNIX_TIMESTAMP()
, it will return the parameter value as the number of seconds since '1970-01-01 00:00:00' GMT.
SELECT UNIX_TIMESTAMP(),UNIX_TIMESTAMP(NOW()),NOW()
FROM_UNIXTIME function: time stamp to date
FROM_UNIXTIME(date)
The function converts the UNIX timestamp into a date and time value in common format, and is the inverse function of the UNIX_TIMESTAMP () function.
SELECT FROM_UNIXTIME(1150051270)
MONTH function: get the month of the specified date
MONTH(date)
The function returns the month corresponding to the specified date, ranging from 1 to 12.
SELECT MONTH('2017-12-15')
MONTHNAME function: Get the English name of the specified date and month
MONTHNAME(date)
The function returns the English full name of the month corresponding to the date date.
SELECT MONTHNAME('2017-12-15')
DAYNAME function: Get the name of the week of the specified date
DAYNAME(date)
The function returns the English name of the working day corresponding to date, such as Sunday, Monday, etc.
SELECT DAYNAME('2006-06-12')
DAYOFWEEK function: Get the week index corresponding to the date
DAYOFWEEK(d)
The function returns the index (position) of the week corresponding to d. 1 means Sunday, 2 means Monday, ..., 7 means Saturday. These index values correspond to the ODBC standard.
SELECT DAYOFWEEK('2017-12-15')
WEEK function: Get the week of the year for the specified date
WEEK()
The function calculates the date date is the week of the year. WEEK(date,mode)
The function allows specifying whether the week starts on Sunday or Monday, and whether the return value ranges from 0 to 52 or 1 to 53.
The WEEK function accepts two parameters:
date is the date for which to get the week number.
mode is an optional parameter that determines the logic for week number calculation.
If the mode parameter is omitted, by default WEEK
the function will use default_week_format
the value of the system variable. To get default_week_format
the current value of the variable, use SHOW VARIABLES
the statement as follows:
SHOW VARIABLES LIKE 'default_week_format'
Use WEEK(date)
the function to query the week of the year for the specified date.
SELECT WEEK('2018-10-25',1)
DAYOFYEAR function: Get the position of the specified date in a year
DAYOFYEAR(d)
The function returns d is the day of the year, ranging from 1 to 366.
SELECT DAYOFYEAR('2017-12-15')
DAYOFMONTH function: Get the position of the specified date in a month
DAYOFMONTH(d)
The function returns d is the day of the month, ranging from 1 to 31.
SELECT DAYOFMONTH('2017-12-15')
YEAR function: get the year
YEAR()
The function can get the year value from the specified date value. YEAR()
The year value returned by the function ranges from 1000 to 9999, if the date is zero, YEAR()
the function returns 0.
SELECT YEAR(NOW())
TIME_TO_SEC function: Convert time to seconds
TIME_TO_SEC(time)
The function returns the time value that converts the parameter time into seconds, and the conversion formula is "hour×3600+minute×60+second".
SELECT TIME_TO_SEC('15:15:15')
SEC_TO_TIME function: Convert seconds value to time format
SEC_TO_TIME(seconds)
The function returns the time value converting the parameter seconds into hours, minutes and seconds.
SELECT SEC_TO_TIME('54925')
DATE_ADD and ADDDATE functions: add a specified time interval to a date
DATE_ADD(date,INTERVAL expr type)
and ADDDATE(date,INTERVAL expr type)
The two functions have the same function, both are used to perform the addition operation of the date.
DATE_ADD()
The and ADDDATE()
function has two parameters:
date is the starting value of DATE or DATETIME.
INTERVAL expr type is the interval value to add to the start date value.
SELECT DATE_ADD('2018-10-31 23:59:59',INTERVAL 1 SECOND) AS C1,
-> DATE_ADD('2018-10-31 23:59:59',INTERVAL '1:1' MINUTE_SECOND) AS C2,
-> ADDDATE('2018-10-31 23:59:59',INTERVAL 1 SECOND) AS C3
SELECT ADDDATE('2017-11-30 23:59:59', INTERVAL 1 SECOND) AS col1,
-> ADDDATE('2017-11-30 23:59:59' ,INTERVAL '1:1' MINUTE_SECOND) AS col2
DATE_SUB and SUBDATE functions: date subtraction
DATE_SUB(date,INTERVAL expr type)
The two functions have SUBDATE(date,INTERVAL expr type)
the same effect as the date subtraction operation.
DATE_SUB()
The and SUBDATE()
function accepts two parameters:
date is the starting value of DATE or DATETIME.
expr is a string that determines the interval value to subtract from the start date. type is the interval unit that expr can resolve, such as DAY, HOUR, etc.
SELECT DATE_SUB('2018-01-02',INTERVAL 31 DAY) AS C1,
-> SUBDATE('2018-01-02',INTERVAL 31 DAY) AS C2,
-> DATE_SUB('2018-01-01 00:01:00',INTERVAL '0 0:1:1' DAY_SECOND) AS C3
Tip: DATE_ADD(date,INTERVAL expr type)
The AND DATE_SUB(date,INTERVAL expr type)
function can also specify a negative value when specifying the time period for addition and subtraction. The negative value of addition returns the date and time before the original time, and the negative value of subtraction returns the date and time after the original time.
ADDTIME function: time addition operation
ADDTIME(time,expr)
function is used to perform the addition operation of time. Add expr to time and return the result.
Where: time is a time or datetime expression and expr is a time expression.
SELECT ADDTIME('2018-10-31 23:59:59','0:1:1'),
-> ADDTIME('10:30:59','5:10:37')
SUBTIME function: time subtraction operation
SUBTIME(time,expr)
Function is used to perform the subtraction of time.
Among them: the function returns time. expr represents the same value as format time. time is a time or datetime expression and expr is a time.
SELECT SUBTIME('2018-10-31 23:59:59','0:1:1'),SUBTIME('10:30:59','5:12:37')
DATEDIFF function: Get the time interval between two dates
DATEDIFF(date1,date2)
Returns the number of days between the start time date1 and the end time date2. date1 and date2 are dates or date-and-time expressions. Only the date portion of these values is used in calculations.
SELECT DATEDIFF('2017-11-30','2017-11-29') AS COL1,
-> DATEDIFF('2017-11-30','2017-12-15') AS col2
WEEKDAY function: Get the index position of the specified date within a week
WEEKDAY(d)
Returns the weekday index corresponding to d. 0 means Monday, 1 means Tuesday, ..., 6 means Sunday.
SELECT WEEKDAY('2017-12-15')
DATE_FORMAT function: format the specified date
MAX function: query the maximum value of the specified column
MIN function: query the minimum value of the specified column
SUM function:
sum COUNT function: count the number of rows of query results
AVG function: calculate the average
See "MySQL Functions (1)" in detail
IF function: judgment
IF
Statements allow you to execute a set of SQL statements based on a condition or value result of an expression.
To form an expression in MySQL, you can combine literals, variables, operators, and even functions. The expression can return TRUE
, FALSE
or NULL
, one of these three values.
SELECT IF(1<2,1,0) c1,IF(1>5,'√','×') c2,IF(STRCMP('abc','ab'),'yes','no') c3
IFNULL function: determine whether it is empty
IFNULL
function is one of the MySQL control flow functions that takes two arguments and NULL
returns the first argument if not. Otherwise, IFNULL
the function returns the second argument. Both arguments can be literal values or expressions.
SELECT IFNULL(5,8),IFNULL(NULL,'OK'),IFNULL(SQRT(-8),'FALSE'),SQRT(-8)
CASE function: search statement
In addition to IF
functions, MySQL also provides an alternative conditional statement CASE
. MySQL CASE
statements make code more readable and efficient.
CASE
Statements come in two flavors: simple and searchable CASE
statements.
Simple CASE statement
A simple CASE
statement means using a simple CASE
statement to check that the value of an expression matches a set of unique values.
The syntax of a simple CASE
statement:
CASE <表达式>
WHEN <值1> THEN <操作>
WHEN <值2> THEN <操作>
...
ELSE <操作>
END CASE;
Where: <expression> can be any valid expression. We compare the value of <expression> with the value in each WHEN
clause , eg <value1>, <value2> etc. If the values of <expression> and <value n> are equal, execute WHEN
the command <action> in the corresponding branch. If WHEN
no <value n> in the clause matches the value of <expression>, the ELSE
commands in the clause will be executed. ELSE
clause is optional. If ELSE
the clause is omitted, and no match is found, MySQL will raise an error.
SELECT CASE WEEKDAY(NOW()) WHEN 0 THEN '星期一' WHEN 1 THEN '星期二' WHEN
2 THEN '星期三' WHEN 3 THEN '星期四' WHEN 4 THEN '星期五' WHEN 5 THEN '星期六'
ELSE '星期天' END AS COLUMN1,NOW(),WEEKDAY(NOW()),DAYNAME(NOW())
searchable CASE statement
Simple CASE
statements only allow matching the value of an expression against a set of distinct values. To perform more complex matches, such as ranges, a searchable CASE
statement can be used. The searchable CASE
statement is equivalent to IF
the statement, but its construct is more readable.
The syntax of a searchable CASE statement:
CASE
WHEN <条件1> THEN <命令>
WHEN <条件2> THEN <命令>
...
ELSE commands
END CASE;
MySQL evaluates WHEN
each condition in the clause separately until it finds one that evaluates to TRUE
, and then executes THEN
the corresponding <command> in the clause. If none of the conditions are true , the <command> in the clause TRUE
is executed . ELSE
If no ELSE
clause is specified, and none of the conditions is met TRUE
, MySQL will issue an error message. MySQL does not allow empty commands in the THEN
or clause. ELSE
If you don't want to deal with ELSE
the logic in the clause, and you want to prevent MySQL from throwing an error, you can put an empty BEGIN END
block in the ELSE clause.
SELECT CASE WHEN WEEKDAY(NOW())=0 THEN '星期一' WHEN WEEKDAY(NOW())=1 THE
N '星期二' WHEN WEEKDAY(NOW())=2 THEN '星期三' WHEN WEEKDAY(NOW())=3 THEN '星期
四' WHEN WEEKDAY(NOW())=4 THEN '星期五' WHEN WEEKDAY(NOW())=5 THEN '星期六' WHEN
WEEKDAY(NOW())=6 THEN '星期天' END AS COLUMN1,NOW(),WEEKDAY(NOW()),DAYNAME(NOW(
))
CAST function: data format conversion
CAST
Function: Perform data format conversion
//语法表达式
CAST(expr AS type)
expr: any valid SQServer expression.
AS: used to separate two parameters, before AS is the data to be processed, after AS is the data type to be converted.
type: The data type provided by the target system.
Example:
SELECT CONCAT(CAST(p.price AS DECIMAL(15,2)),'%') AS PricePercent FROM Persons p
result
DECIMAL function: number manipulation
语法:
DECIMAL(a,b)
a: Specifies the maximum number of decimal digits that can be stored on the left and right sides of the specified decimal point, with a maximum precision of 38; generally speaking, it is the maximum number of digits that can be displayed by adding the left and right sides.
b: Specifies the maximum number of decimal digits that can be stored on the right side of the decimal point. The decimal place must be a value between 0 and a. The default decimal place is 0. In layman's terms, it is the largest number of digits displayed by the numbers after the decimal point.
Note: The maximum number of digits displayed by a number is not a reserved number of digits. If there are not so many digits, just display the current number, and there is no need to forcibly fill in the digits.
For example:
(1) There is a number 123456789.12345.
If you use decimal (10, 1), the displayed result is: 123456789.1
If you use decimal (11, 2), the displayed result is: 123456789.12
If you use decimal (10, 2), the displayed result is: 99999999.99 (Because of the loss of precision. It is required that there can only be a maximum of 10 digits on the left and right sides. There are already 9 digits in the front, and there can only be one more digit in the back, but it is required to keep 2 digits in the back, so it can only be specified.
(2) If there is a number 123,
if you use decimal (3, 2), the result will be 123.
If you use decimal (10, 1), the result will be 123.
If you use decimal (9, 2), the result will be 123. The result is 123.
If decimal (2, 2) is used to display the result is 0.99
LIMIT function: extract the first few or some rows of data in the middle
//语法
LIMIT n,m
//其中m是指记录开始的index,从0开始,表示第一条记录;n是指从m+1条开始,取n条。
select * from table LIMIT m,n;
//即取出第3条至第6条,4条记录。
select * from table LIMIT 2, 4;
//取前五个:
LIMIT 0, 5;等同于LIMIT 5;
Note:limit
Not universal, it is specific to mysql, not in other databases; limit
it is a link in the final execution of sql statements.