Complete and practical use of MySQL functions

Table of contents

1. Introduction to MySQL functions

Two, MySQL function classification

(1) One-line function

① String function

②Mathematical functions

③Date function

④ Process control function

⑤ System information function

⑥Other functions

(2) Aggregation function

3. Examples of function usage

(1) Character functions

① length (str) function

②concat(str1, str2,...) function

③upper(str), lower(str) function

④ substr (str, start, len) function

⑤instr(str, the substring to be searched) function

③trim(str) function

⑧lpad(str, len, filling character), rpad(str, len, filling character) function

⑨replace(str, substring, another string) function

(2) Mathematical functions

①round(x, reserved digits) function

②ceil(x) function

③floor(x) function

④truncate(x,D) function

⑤ mod (dividend, divisor) function

⑥pow(x,D) function

 (3) Time and date functions

① Meaning of time and date functions

②now() function

③curdate() function

④ curtime () function

⑤ Get the year, month, day, hour, minute, and second in the date and time

⑥weekofyear() function

⑦ quarter() function

⑧ str_to_date() function

⑨date_format() function

⑩date_add(date, interval num time) function

⑪last_day() function

⑫ datediff (end_date, start_date) function

⑬timestampdiff(unit, start_date, end_date) function

(4) Process control function

①if(expr,v1,v2) function

②ifnull() function

③Three usages of case...when function

(5) System information function

①version() function

②connection_id() function

③processlist

④database(), schema() function

⑤user(), current_user(), system_user() function

⑥ charset () function

⑦collation() function

(6) Other functions

①FORMAT(x,y) function

② INET_ATON(ip) function

③INET_NTOA(NUM) function

④ password (str) function

⑤md5(str) function

⑥encode (str, pswd_str), decode (encrypted string, pswd_str) function

(7) Aggregation functions

①Function and classification

②Incoming parameters and data types of aggregation functions


1. Introduction to MySQL functions

MySQL is an internal function provided by the MySQL database. These internal functions can help users process data in tables more conveniently. Functions are stored in the database like predetermined formulas, and each user can call existing functions to complete certain functions.

At the same time, the MySQL database also supports users to create their own functions to adapt to actual business operations. Proper use of functions will allow readers to get twice the result with half the effort when writing SQL statements.

Two, MySQL function classification

(1) One-line function

① String function

Primarily used for manipulating strings. These include string concatenation functions, string comparison functions, functions that convert all letters of a string to lowercase or uppercase, and functions that obtain substrings.

②Mathematical functions

Primarily used for manipulating numbers. Such functions include absolute value functions, sine functions, cosine functions, and functions for obtaining random numbers, etc.

③Date function

Primarily used for working with dates and times. These include functions to get the current time, functions to get the current date, functions to return a year, functions to return a date, and more.

④ Process control function

It is mainly used to control conditional selection in SQL statements. These include IF statements, CASE statements, and WHERE statements

⑤ System information function

It is mainly used to obtain the system information of the MySQL database. These include a function to get the database name, a function to get the current user, a function to get the database version, and so on.

⑥Other functions

It mainly includes formatting functions and lock functions.

(2) Aggregation function

AVG (average value) function: Returns the average value of the specified group, and null values ​​are ignored.

COUNT (statistical) function: returns the total number of items in the specified group.

MAX (maximum value) function: Returns the maximum value of the specified data.

MIN (minimum value) function: Returns the minimum value of the specified data.

SUM (summation) function: returns the sum of the specified data, can only be used for numeric columns, and null values ​​will be ignored.

3. Examples of function usage

(1) Character functions

① length (str) function

Get the number of bytes of the parameter value

For utf-8the character set, one English occupies 1 byte; one Chinese occupies 3 bytes;

For gbkthe character set, one English occupies 1 byte; one Chinese occupies 2 bytes;

The demonstration is as follows:

select length('关注作者') as 长度;

②concat(str1, str2,...) function

Splice the strings, and splice them into a string through the input parameters str1, str2, etc.

The demonstration is as follows:

select concat('作者','-','Sheenky') as 作者信息;

③upper(str), lower(str) function

upper(str): Change all letters in the character to uppercase

lower(str) converts all letters in the character to lowercase

The demonstration is as follows:

select upper('sheenky') as 大写;
select lower('SHEENKY') as 小写;

④ substr (str, start, len) function

str is the input string, and the string is intercepted from the start position, and len indicates the length to be intercepted; if the length of len is not specified: it indicates that the string is intercepted from the start to the end of the string. The length of len is specified: it means to intercept the length of len from start.

select substr('学SQL就关注博主sheenky',2,8) as out_put;

Note: 2 is the starting position, where the starting position is 'learning' and the corresponding position is 1, which is different from the starting position of 0 in the programming language.

In addition, 8 is the length from the start to the end position, not the end position of the index, which is easy to confuse with Python's index.

⑤instr(str, the substring to be searched) function

Return the index of the first occurrence of the substring, if not found, return 0; When the searched substring exists in the string: return the index of the [first] occurrence of the substring in the string. When the searched substring is not in the string: return 0.

The demonstration is as follows:

select instr('学SQL就关注博主sheenky','关注') as 第一次出现;

③trim(str) function

Remove the spaces before and after the string; This function can only remove the spaces before and after the string, but not the spaces in the middle of the string.

The demonstration is as follows:

select trim(' 学SQL就 关注博主 sheenky ') as 空格去除;

 ⑧lpad(str, len, filling character), rpad(str, len, filling character) function

lpad (left padding): Use the specified character to realize the left padding of the string to the specified length

rpad (right padding): Use the specified character to realize the right padding of the string to the specified length

select lpad('编程秃头',10,'tu') as out_put;
select rpad('编程秃头',10,'tu') as out_put;

 Note: The padding len here refers to the total length after filling with padding characters, that is, if your len selects 5 and your string contains a position of 4, only one character can be filled, that is, the first character of the padding character .

⑨replace(str, substring, another string) function

Replace the string in the string str with another string

The demonstration is as follows:

select replace(NAME,'符兴','符强') as 替换之后 from tb_teacher;

 Note: The replace() method can only search for specified columns, but cannot use global search. If you want to find and replace globally, you can try a loop statement.

(2) Mathematical functions

①round(x, reserved digits) function

Rounding; When rounding positive numbers: according to the normal calculation method, rounding is sufficient. When rounding a negative number: first throw the sign aside, round the positive number after removing the negative sign, and then fill in the negative sign after completion.

The demonstration is as follows:

select round(1.595658,3) as out_put;

②ceil(x) function

Round up and return the smallest integer >= the parameter. Find the smallest integer greater than or equal to this number

The demonstration is as follows:

select ceil(1.9) as out_put;
select ceil(1.1) as out_put;

③floor(x) function

Round down, return the largest integer <= the parameter, and find the largest integer less than or equal to this number.

The demonstration is as follows:

select floor(1.99) as out_put;
select floor(1.1) as out_put;

④truncate(x,D) function

This function is called the truncation function, as the name implies, it is to intercept the unnecessary part, and then delete (break) it. At the D position of the decimal point, the number is intercepted and the number is directly deleted. If it is on the left, the position is rounded without using any rules.

This function is not difficult to understand, we treat truncate as a decimal point (.) x is the number to be intercepted. When D is a positive number, it is the right part of the decimal point. When D is 0, the decimal part is not needed. When D is negative, it is the part to the left of the decimal point. See the example demonstration for specific usage.

The demonstration is as follows:

select truncate(314159.2673525,5) as 截取之后;
select truncate(314159.2673525,0) as 截取之后;
select truncate(314159.2673525,-4) as 截取之后;

 ⑤mod(被除数,除数)函数

Take the remainder; when the dividend is positive, the result is positive. When the dividend is negative, the result is negative.

The demonstration is as follows:

select mod(10,3) as out_put;

⑥pow(x,D) function

This function is used to calculate the exponential function, x is the base, and D is the exponent

The demonstration is as follows:

select pow(5,2) as 平方运算;

 (3) Time and date functions

① Meaning of time and date functions

The meaning of date: refers to the year, month, and day we often say.

The meaning of time: refers to the hours, minutes, and seconds we often say.

Supplementary Time Format Symbol Meaning Table

serial number format character meaning
1 %Y four digit year
2 %y 2 digit year
3 %m month(01,02,..11,12)
4 %c month (1,2,3...11,12)
5 %d day (01,02,...)
6 %H hours (24 hours)
7 %h hours (12 hours)
8 %i minutes (00,01,...59)
9 %s seconds (00,01,...59)

②now() function

Returns the current system date and time

The demonstration is as follows:

select now() as 当前时间;

③curdate() function

Only return the current date of the system, not including the time

The demonstration is as follows:

select surdate() as 当前日期;

 ④ curtime () function

Returns only the current time, without the date

The demonstration is as follows:

⑤ Get the year, month, day, hour, minute, and second in the date and time

Get the year: year()

Get the month: month()

Get day: day()

Get the hour: hour()

Get minutes: minute()

Get seconds: second()

⑥weekofyear() function

Get the week number of the current moment

The demonstration is as follows:

⑦ quarter() function

Get the quarter to which the current moment belongs

⑧ str_to_date() function

Convert the date format to a string, and convert it to a date in the specified format

⑨date_format() function

Convert date to date string

 ⑩date_add(日期,interval num 时间)函数

Offset the date and time forward and backward, the positive sign is backward, the negative sign is forward, in addition to hour (hour), minute (minute), second (second)

⑪last_day() function

Extract the date of the last day of a month

 ⑫ datediff (end_date, start_date) function

Calculate the number of days between two dates

The demonstration is as follows:

 ⑬timestampdiff(unit,start_date,end_date)函数

Calculate the number of years/months/days returned by two times;

The unit parameter is the unit to determine the result of (start_date, end_date), expressed as an integer, the following are valid units:

year: year, month: month, day: day, hour: hour, minute minute, second: second, microsecond: microsecond, week: week number, quarter: quarter

(4) Process control function

①if(expr,v1,v2) function

Realize the effect of if-else, if expr is true, return v1. If expr is false, return v2

The demonstration is as follows

 ②ifnull() function

Determine whether the value is null, if it is null, fill it with the specified value; if v1 is not NULL, return v2. Otherwise return v1

 ③Three case…whenusages of functions

1. Equivalence judgment: it can realize multi-condition query value selection;

case field or expression to be judged
when constant 1 then value 1 or statement 1 to be displayed
when constant 2 then value 2 to be displayed or statement 2
...
else value n to be displayed or statement n
end

2. Interval judgment: similar to the effect of if-elif-else in python;

case
when condition 1 then value 1 to be displayed or statement 1
when condition 2 then value 2 to be displayed or statement 2
...
else value n to be displayed or statement n
end

3. case ... when is used in conjunction with aggregate functions;

In the example here, the author cites an example on the Internet as an example

 The following results are obtained:

(5) System information function

①version() function

View the MySQL system version information number

②connection_id() function

View the number of connections of the currently logged in user

Directly call the CONNECTION_ID() function -- without any parameters -- to see the current number of connections to the MySQL server. The return value of this function may be different in different time periods

③processlist

View user connection information

Id column: the user ID for logging in to MySQL, which is the CONNECTION ID automatically assigned by the system;

User column: display the current "user name";

Host column: Displays the IP that executes this statement, which is used to track the user who has the problem statement;

db column: shows which database the process is currently connected to;

Command column: Displays the commands executed by the current connection, generally sleep (Sleep), query (Query), and connection (Connect);

Time column: Displays the duration of this state, in seconds;

State column: Displays the status of the SQL statement using the current connection, including: Copying to tmptable, Sorting result, Sending data, etc.;

Info column: Display the content of the current SQL, if the statement is too long, it may not be displayed completely.

 ④database(), schema() function

View the currently used database

 ⑤user(), current_user(), system_user() function

get current user

⑥ charset () function

Use CHARSET()a function to return the character set used by a string

 ⑦collation() function

Using COLLATION()a function to return a string permutation

(6) Other functions

①FORMAT(x,y) function

Format x as a comma-separated sequence of numbers, and y is the number of decimal places for the result.

② INET_ATON(ip) function

Returns a numeric representation of the IP address

③INET_NTOA(NUM) function

Returns the IP address represented by the number.

 ④ password (str) function

Password encryption function, if str is NULL, return NULL.
password is used in the MySQL server authentication system. Should not be used in personal applications.
Encryption is one-way (irreversible), and the encrypted password is stored in the user permission table.
Enforcing password encryption is different from the way passwords are encrypted in UNIX.

⑤md5(str) function

encryption function;

The parameter is a string, and this function calculates an MD5 128-bit checksum for the string. The
return value is a binary string of 32 hexadecimal numbers. Return
str is NULL, and return NULL

 ⑥encode (str, pswd_str), decode (encrypted string, pswd_str) function

Encryption: encode(encrypted password, password);

Decryption: decode(encode(encrypted password, password), password); //You can also use the binary string returned above

(7) Aggregation functions

①Function and classification

Function: used for statistics, also known as aggregation function or statistical function or group function

Classification: sum sum avg average value max maximum value min minimum value count calculation number

 ②Incoming parameters and data types of aggregation functions

1. The sum() function and avg() function: it only makes sense to pass in the integer/decimal type;

2. The sum() function and avg() function are not very meaningful for the calculation of string type and date/time type. Therefore, the sum() function and avg() function are only used to sum decimal types and integer types. Skip empty rows.

3. max() function and min() function: it is more meaningful to pass in integer/decimal type and date/time type

4. You can pass in any data type, but you should pay attention to null values. Null values ​​are skipped and not counted.

Note; when the sum()/count(*) method calculates the average value, sometimes the result obtained is not necessarily the same as the AVG() function. When there is a null value in a calculated column but other columns are not null, different results will appear, because the denominator count(*) does not skip the null column.

Guess you like

Origin blog.csdn.net/Sheenky/article/details/125142451