当前位置:网站首页>MySQL learning (from getting started to mastering 1.2)

MySQL learning (from getting started to mastering 1.2)

2022-06-21 21:05:00 if you never leave me, i will be with you till death do us apart

Docking from entry to mastery 1.1

The fifth chapter Multi-table query

Multi-table query , Also known as associative queries , It means that two or more tables complete the query operation together .
Prerequisite : There is a relationship between these tables queried together ( one-on-one 、 One to many ), There must be associated fields between them , This
The associated field may have established a foreign key , Or you may not have established a foreign key . such as : Employee table and department table , These two tables depend on “ Department number ” Into the
Row Association .

1. Multi table connection caused by a case

1.1 Case description

 Insert picture description here
Getting data from multiple tables :
 Insert picture description here
Query results :

+-----------+----------------------+
| last_name | department_name |
+-----------+----------------------+
| King | Administration |
| King | Marketing |
| King | Purchasing |
| King | Human Resources |
| King | Shipping |
| King | IT |
| King | Public Relations |
| King | Sales |
| King | Executive |
| King | Finance |
| King | Accounting |
| King | Treasury |
...
| Gietz | IT Support |
| Gietz | NOC |
| Gietz | IT Helpdesk |
| Gietz | Government Sales |
+-----------+----------------------+
2889 rows in set (0.01 sec)

Analyze the error :

SELECT COUNT(employee_id) FROM employees;
# Output 107 That's ok 
SELECT COUNT(department_id)FROM departments;
# Output 27 That's ok 
SELECT 107*27 FROM dual

We call the problem in the above multi table query as : The error of Cartesian product .

1.2 The cartesian product ( Or cross connect ) The understanding of the

Cartesian product is a mathematical operation . Suppose I have two sets X and Y, that X and Y The Cartesian product of is X and Y All possible combinations of , That is, the first object comes from X, The second object comes from Y All the possibilities of . The number of combinations is the product of the number of elements in the two sets .

 Insert picture description here
SQL92 in , Cartesian product is also called Cross connect , English is CROSS JOIN . stay SQL99 It is also used in CROSS JOIN Express delivery
Fork connection . Its function is to connect any table , Even if the two tables are not related . stay MySQL Cartesian product will appear in the following cases :

# Query employee name and department name 
SELECT last_name,department_name FROM employees,departments;
SELECT last_name,department_name FROM employees CROSS JOIN departments;
SELECT last_name,department_name FROM employees INNER JOIN departments;
SELECT last_name,department_name FROM employees JOIN departments

The error of Cartesian product will occur under the following conditions :
Omit join conditions for multiple tables ( Or related conditions )
Connection condition ( Or related conditions ) Invalid
All rows in all tables are interconnected

To avoid Cartesian product , Can be in WHERE Add a valid connection condition .
After adding connection conditions , The query syntax :

SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2; # Connection condition 

stay WHERE Clause .
stay WHERE Clause .

# Case study : Query the employee's name and department name 
SELECT last_name, department_name
FROM employees, departments
WHERE employees.department_id = departments.department_id

When there are the same columns in the table , Prefix the column name with the table name .

2. Multi table query classification explanation

classification 1: Equivalent connection vs Non equivalent connection
Equivalent connection

 Insert picture description here

departments.location_id
FROM employees, departments
WHERE employees.department_id = departments.department_id;

 Insert picture description here

expand 1: Multiple connection conditions and AND The operator

 Insert picture description here
expand 2: Distinguish between duplicate column names
When there are the same columns in multiple tables , The column name must be prefixed with the table name .
Columns with the same column name in different tables can be used Table name Distinguish .

SELECT employees.last_name, departments.department_name,employees.department_id
FROM employees, departments
WHERE employees.department_id = departments.department_id;

expand 3: The table alias

Using aliases can simplify queries .
Using table name prefix before column name can improve query efficiency .

SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e , departments d
WHERE e.department_id = d.department_id;

It should be noted that , If we use the alias of the table , In the query field 、 Only aliases can be used in the filter conditions , Cannot use the original table name , Otherwise you will report an error . 【 mandatory
】 For queries and changes to table records in the database , As long as multiple tables are involved , You need to add the alias of the table before the column name ( Or watch name ) To limit . explain
: Query records for multiple tables 、 Update record 、 When deleting records , If there is no alias of the qualified table for the operation column ( Or watch name ), And when the operation column exists in multiple tables , I'm going to throw an exception . Example
:select t1.name from table_first as t1 , table_second as t2 where
t1.id=t2.id; Counter example : In a business , Because the multi table associated query statement does not add the alias of the table ( Or watch name ) The limitation of , Two years after normal operation , Recently
Add a field with the same name to a table , After making database changes in the pre release environment , The online query statement appears 1052 abnormal :Column ‘name’ in field
list is ambiguous.

expand 4: Join multiple tables

 Insert picture description here
summary : Connect n Tables , Need at least n-1 Connection conditions . such as , Join three tables , At least two join conditions are required .
practice : Query the employee's last_name,department_name, city

Non equivalent connection
 Insert picture description here

WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal;

 Insert picture description here

classification 2: Self join vs Non self connecting

 Insert picture description here
When table1 and table2 It's essentially the same table , Just use the alias to form two virtual tables to represent different meanings . Then the two tables are connected internally , External connection and other queries .

subject : Inquire about employees surface , return “Xxx works for Xxx”

SELECT CONCAT(worker.last_name ,' works for '
, manager.last_name)
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id ;

 Insert picture description here

practice : Query out last_name by ‘Chen’ Of our employees manager Information about .

In addition to querying the records that meet the conditions , External join can also query records that one party does not meet the conditions .

 Insert picture description here
Internal connection : Merging rows of more than two tables with the same column , There are no rows in the result set that do not match one table with another
External connection : In addition to the rows that meet the connection conditions, the two tables also return the left ( Or right ) Rows in the table that do not meet the criteria , This connection is called left ( Or right ) External connection . When there are no matching rows , The corresponding column in the result table is empty (NULL).
If it's a left outer connection , The table on the left of the join condition is also called Main table , The table on the right is called From the table .
If it's a right outer connection , The table on the right in the join condition is also called Main table , The table on the left is called From the table .

SQL92: Use (+) Create connection
stay SQL92 Used in (+) Represents the location of the slave table . That is, in the left or right outer connection ,(+) Indicates which is from the table .
Oracle Yes SQL92 Better support , and MySQL Do not support SQL92 External connection of .

# The left outer join 
SELECT last_name,department_name
FROM employees ,departments
WHERE employees.department_id = departments.department_id(+);
# Right connection 
SELECT last_name,department_name
FROM employees ,departments
WHERE employees.department_id(+) = departments.department_id

And in SQL92 in , Only the left outer connection and the right outer connection , Not full ( Or all ) External connection .

3. SQL99 Syntax to implement multi table query

Use JOIN…ON Clause creates the syntax structure of the join :

SELECT table1.column, table2.column,table3.column
FROM table1
JOIN table2 ON table1  and  table2  The connection condition of 
JOIN table3 ON table2  and  table3  The connection condition of 

Its nesting logic is similar to what we use FOR loop :

for t1 in table1:
for t2 in table2:
if condition1:
for t3 in table3:
if condition2:
output t1 + t2 + t3

SQL99 This nested structure is very refreshing 、 More hierarchical 、 More readable , Even if more tables are connected, they are clearly visible . If you take SQL92, Readability will be greatly reduced .

Syntax description :
have access to ON Clause specifies additional join conditions .
This connection condition is separate from other conditions .
ON Clause makes the statement more readable .
keyword JOIN、INNER JOIN、CROSS JOIN It means the same thing , Both represent internal connections

3.2 Internal connection (INNER JOIN) The implementation of the

grammar :

SELECT  Field list 
FROM A surface  INNER JOIN B surface 
ON  The associated condition 
WHERE  And so on ;

subject 1:

SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);

 Insert picture description here
subject 2:

JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;

 Insert picture description here

3.3 External connection (OUTER JOIN) The implementation of the

3.3.1 The left outer join (LEFT OUTER JOIN)

grammar :

# The query result is A
SELECT  Field list 
FROM A surface  LEFT JOIN B surface 
ON  The associated condition 
WHERE  And so on ;

give an example :

SELECT e.last_name, e.department_id, d.department_name
FROM employees e
LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

 Insert picture description here
3.3.2 Right connection (RIGHT OUTER JOIN)
grammar :

FROM A surface  RIGHT JOIN B surface 
ON  The associated condition 
WHERE  And so on 

give an example :

SELECT e.last_name, e.department_id, d.department_name
FROM employees e
RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;

 Insert picture description here

It should be noted that ,LEFT JOIN and RIGHT JOIN Is only found in SQL99 And later standards , stay SQL92 Does not exist in the , Only use (+) Express .

3.3.3 Full outer join (FULL OUTER JOIN)
The result of full external connection = Data matching the left and right tables + There is no matching data in the left table + There is no matching data in the right table .
SQL99 It supports full external connection . Use FULL JOIN or FULL OUTER JOIN To achieve .
It should be noted that ,MySQL I won't support it FULL JOIN, But you can use LEFT JOIN UNION RIGHT join Instead of .

4. UNION Use

Merge query results utilize UNION keyword , You can give more than one SELECT sentence , And combine their results into a single result set . When merging , The number of columns and data types of the two tables must be the same , And correspond to each other . each SELECT Use... Between statements UNION or UNIONALL Keyword separation .

Grammar format :

SELECT column,... FROM table1
UNION [ALL]
SELECT column,... FROM table2

UNION The operator

 Insert picture description here

Be careful : perform UNION ALL Statement requires more resources than UNION Few statements . If you know clearly that there is no duplicate data in the result data after data consolidation , Or you don't need to remove duplicate data , Try to use UNION ALL sentence , To improve the efficiency of data query .

give an example : Check department number >90 Or the mailbox contains a Employee information

# The way 1
SELECT * FROM employees WHERE email LIKE '%a%' OR department_id>90;
# The way 2
SELECT * FROM employees WHERE email LIKE '%a%'
UNION
SELECT * FROM employees WHERE department_id>90;

give an example : Query the information of men in Chinese users and middle-aged men in American users

SELECT id,cname FROM t_chinamale WHERE csex=' male '
UNION ALL
SELECT id,tname FROM t_usmale WHERE tGender='male';

5. 7 Kind of SQL JOINS The implementation of the

 Insert picture description here

5.7.1 Code implementation

# Chinese : Internal connection  A∩B
SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`;
# Top left : The left outer join 
SELECT employee_id,last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Top right : Right connection 
SELECT employee_id,last_name,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Middle left :A - A∩B
SELECT employee_id,last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
# Middle right :B-A∩B
SELECT employee_id,last_name,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL
SELECT employee_id,last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
UNION ALL # No de duplication operation , Efficient 
SELECT employee_id,last_name,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`;
# Bottom right 
# Middle left  +  Middle right  A ∪B- A∩B  perhaps  (A - A∩B) ∪ (B - A∩B)
SELECT employee_id,last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE d.`department_id` IS NULL
UNION ALL
SELECT employee_id,last_name,department_name
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
WHERE e.`department_id` IS NULL

5.7.2 Syntax format summary

Middle left

# Realization A - A∩B
select  Field list 
from A surface  left join B surface 
on  The associated condition 
where  Associate fields from the table  is null and  And so on ;

Middle right

# Realization B - A∩B
select  Field list 
from A surface  right join B surface 
on  The associated condition 
where  Associate fields from the table  is null and  And so on ;

Bottom left

# The query result is A∪B
# Use the left outside A,union  Right outside B
select  Field list 
from A surface  left join B surface 
on  The associated condition 
where  And so on 
union
select  Field list 
from A surface  right join B surface 
on  The associated condition 
where  And so on ;
# Realization A∪B - A∩B  or  (A - A∩B) ∪ (B - A∩B)
# Use the left outside  (A - A∩B) union  Right outside (B - A∩B)
select  Field list 
from A surface  left join B surface 
on  The associated condition 
where  Associate fields from the table  is null and  And so on 
union
select  Field list 
from A surface  right join B surface 
on  The associated condition 
where  Associate fields from the table  is null and  Wait for others 

6. SQL99 New features of grammar

6.1 Natural join

SQL99 stay SQL92 Provides some special syntax based on , such as NATURAL JOIN Used to represent natural connections . We can understand natural connection as SQL92 The equivalent connection in . It will help you automatically query the two connection tables All the same fields , Then proceed Equivalent connection .

stay SQL92 In the standard :

SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`
AND e.`manager_id` = d.`manager_id`;

stay SQL99 You can write :

SELECT employee_id,last_name,department_name
FROM employees e NATURAL JOIN departments d;

6.2 USING Connect

When we connect ,SQL99 Also supports the use of USING Specify... In the data table Fields with the same name Make an equivalent connection . But only with JOIN Use it together . such as :

SELECT employee_id,last_name,department_name
FROM employees e JOIN departments d
USING (department_id)

You can see the connection with nature NATURAL JOIN The difference is ,USING Specifies the specific same field name , You need to USING The brackets of () Fill in the field with the same name to be specified . Use at the same time JOIN…USING Can be simplified JOIN ON Equivalent connection . It is related to the following SQL The query results are the same :

SELECT employee_id,last_name,department_name
FROM employees e ,departments d
WHERE e.department_id = d.department_id;

There are three ways to constrain table joins :WHERE, ON, USING

WHERE: Applicable to all associated queries ON
ON : And the only JOIN Use it together , Only association conditions can be written . Although Association conditions can be combined to WHERE Write... With other conditions , But it's better to write separately .
USING: And the only JOIN Use it together , Moreover, the names of the two associated fields should be consistent in the associated table , And it can only mean that the associated field values are equal

# The associated condition 
# Write the correlation condition in where Back 
SELECT last_name,department_name
FROM employees,departments
WHERE employees.department_id = departments.department_id;
# Write the correlation condition in on Back , And the only JOIN Use it together 
SELECT last_name,department_name
FROM employees INNER JOIN departments
ON employees.department_id = departments.department_id;
SELECT last_name,department_name
FROM employees CROSS JOIN departments
ON employees.department_id = departments.department_id;
SELECT last_name,department_name
FROM employees JOIN departments
ON employees.department_id = departments.department_id;
# Write the associated fields in using() in , And the only JOIN Use it together 
# And the associated fields in the two tables must have the same name , And it can only mean =
# Query employee name and basic salary 
SELECT last_name,job_title
FROM employees INNER JOIN jobs USING(job_id);
#n Zhang table correlation , need n-1 Two association conditions 
# Check the name of the employee , Basic salary , Department name 
SELECT last_name,job_title,department_name FROM employees,departments,jobs
WHERE employees.department_id = departments.department_id
AND employees.job_id = jobs.job_id;
SELECT last_name,job_title,department_name
FROM employees INNER JOIN departments INNER JOIN jobs
ON employees.department_id = departments.department_id
AND employees.job_id = jobs.job_id;

Be careful :
We want to Control the number of join tables . Multiple table join is equivalent to nesting for The cycle is the same , Very resource intensive , Will make SQL Query performance has been severely degraded , So don't join unnecessary tables . In many DBMS in , There will also be a limit on the maximum connection table .

【 mandatory 】 More than three tables prohibited join. need join Field of , Data types are absolutely consistent ; When multi table associated query , Protect The fields associated with the certificate need to have an index .
explain : Even if the double meter join Also pay attention to table indexes 、SQL performance . source : Alibaba 《Java Development Manual 》

appendix : frequently-used SQL What are the standards? When we formally start talking about the types of connection tables , We need to know first SQL There are different versions of standard specifications , Because the tables under different specifications

The connection operation is different .
SQL There are two main criteria , Namely SQL92 and SQL99 .92 and 99 Represents the time when the standard was proposed ,SQL92 Namely 92 Standards and specifications proposed in . Except, of course, SQL92 and SQL99 outside , There is still SQL-86、SQL-89、SQL:2003、SQL:2008、

SQL:2011 and SQL:2016 Other standards .

So many standards , Which should we learn ?

Actually, the most important thing is SQL The standard is SQL92 and SQL99. Generally speaking SQL92 The form is simpler , But it's written SQL The statements will be longer , Poor readability . and SQL99 Compared with SQL92 Come on , The grammar is more complicated , But more readable . We can also see from the number of pages published by these two standards ,SQL92 There are 500 page , and SQL99 The standard exceeds
1000 page . Actually from SQL99 after , Few people can master all the content , Because there are so many . It's like we use Windows、Linux and Office When , Few people can master all the content . We just need to master some core functions , Just meet the needs of daily work .
SQL92 and SQL99 It's classic SQL standard , Also called SQL-2 and SQL-3 standard . It was after the release of these two standards ,SQL More and more influence , Even beyond the database field . Today, SQL It is not only the mainstream language in the field of database , It is also the mainstream language of information processing in the information field . In graphics retrieval 、 Image retrieval and voice retrieval can see SQL The use of language .

The first 07 Chapter _ A separate letter

1. The understanding of function

1.1 What is a function

Function runs through the use of computer language , What does the function do ? It can encapsulate the code we often use , Call directly when necessary . This is both Improved code efficiency , also Improved maintainability . stay SQL In, we can also use functions to operate on the retrieved data . Use these functions , Can greatly Improve the efficiency of user management of database .

 Insert picture description here
From the perspective of function definition , We can divide the function into Built in functions and Custom function . stay SQL In language , It also includes built-in functions and custom functions . Built in function is a general function built in the system , The custom function is written according to our own needs , This chapter and the next chapter explain SQL Built in functions for .

1.2 Different DBMS The difference between functions

We are using SQL When it comes to language , Not dealing directly with the language , Instead, it uses different database software , namely DBMS.DBMS There are great differences between , Much greater than the difference between different versions of the same language . actually , Only a few functions are called DBMS Supported at the same time . such as , majority DBMS Use (||) perhaps (+) To make a splice , And in the MySQL The string splicing function in is concat(). Most of the DBMS Will have their own specific functions , This means adopting SQL The code portability of functions is very poor , Therefore, special attention should be paid to when using functions .

MySQL Provides a wealth of built-in functions , These functions make data maintenance and management more convenient , It can better provide data analysis and statistical functions , To some extent, it improves the efficiency of data analysis and Statistics .

MySQL The built-in functions provided are from From the perspective of function Can be divided into numerical functions 、 String function 、 Date and time functions 、 Process control functions 、 Encryption and decryption functions 、 obtain MySQL Information functions 、 Aggregate functions, etc . here , I subdivide these rich built-in functions into two categories : One line function 、 Aggregate functions ( Or grouping function ) .

Two kinds of SQL function

 Insert picture description here
One line function

Manipulate data objects
Accept parameters and return a result
Change only one line
Each line returns a result
Can be nested
The parameter can be a column or a value

2. Numerical function

2.1 Basic functions

ABS(x) return x The absolute value of
SIGN(X) return X The symbol of . A positive number returns 1, A negative number returns -1,0 return 0
PI() Returns the value of the pi
CEIL(x),CEILING(x) Returns the smallest integer greater than or equal to a value
FLOOR(x) Returns the largest integer less than or equal to a value
LEAST(e1,e2,e3…) Returns the minimum value in the list
GREATEST(e1,e2,e3…) Returns the maximum value in the list
MOD(x,y) return X Divide Y Remainder after
RAND() return 0~1 The random value
RAND(x) return 0~1 The random value , among x The value of is used as the seed value , same X Values produce the same random number
ROUND(x) Returns a pair x After rounding the value of , Closest to X The integer of
ROUND(x,y) Returns a pair x The value of is rounded to the nearest X Value , And keep it after the decimal point Y position
TRUNCATE(x,y) Return to digital x Truncated to y The result of decimal places
SQRT(x) return x The square root of . When X When the value of is negative , return NULL

give an example :

SELECT
ABS(-123),ABS(32),SIGN(-23),SIGN(43),PI(),CEIL(32.32),CEILING(-43.23),FLOOR(32.32),
FLOOR(-43.23),MOD(12,5)
FROM DUAL;
SELECT RAND(),RAND(),RAND(10),RAND(10),RAND(-1),RAND(-1)
FROM DUAL;
SELECT
ROUND(12.33),ROUND(12.343,2),ROUND(12.324,-1),TRUNCATE(12.66,1),TRUNCATE(12.66,-1)
FROM DUAL;
function usage
RADIANS(x) Convert angles to radians , among , Parameters x Is the angle value
DEGREES(x) Convert radians to angles , among , Parameters x Is the radian value
SELECT RADIANS(30),RADIANS(60),RADIANS(90),DEGREES(2*PI()),DEGREES(RADIANS(90))
FROM DUAL;

2.3 Trigonometric functions

function usage
SIN(x) return x The sine of , among , Parameters x Is the radian value
ASIN(x) return x The arcsine of , That is, the sine obtained is x Value . If x The value of is not in -1 To 1 Between , Then return to NULL
COS(x) return x Cosine of , among , Parameters x Is the radian value
ACOS(x) return x The arccosine of , That is, get the cosine as x Value . If x The value of is not in -1 To 1 Between , Then return to NULL
TAN(x) return x The tangent of , among , Parameters x Is the radian value
ATAN(x) return x The arctangent of , That is, the tangent value returned is x Value
ATAN2(m,n) Returns the arctangent of two parameters
COT(x) return x Cotangent of , among ,X Is the radian value

give an example :

ATAN2(M,N) Function returns the arctangent of two parameters . And ATAN(X) Compared to the function ,ATAN2(M,N) Two parameters are required , For example, there are two points point(x1,y1) and point(x2,y2), Use ATAN(X) The function calculates the arctangent as ATAN((y2-y1)/(x2-x1)), Use ATAN2(M,N) Calculate the arctangent as ATAN2(y2-y1,x2-x1). It can be seen from the way of use , When x2-x1 be equal to 0 when ,ATAN(X) The function will report an error , and ATAN2(M,N) Function can still calculate .

ATAN2(M,N) An example of using the function is as follows :

ATAN2(M,N) An example of using the function is as follows :
SELECT RADIANS(30),RADIANS(60),RADIANS(90),DEGREES(2*PI()),DEGREES(RADIANS(90))
FROM DUAL;
SELECT
SIN(RADIANS(30)),DEGREES(ASIN(1)),TAN(RADIANS(45)),DEGREES(ATAN(1)),DEGREES(ATAN2(1,1)
)
FROM DUAL;

 Insert picture description here

function usage
POW(x,y),POWER(X,Y) return x Of y Power
EXP(X) return e Of X Power , among e It's a constant ,2.718281828459045
LN(X),LOG(X) Return to e At the bottom of the X The logarithmic , When X <= 0 when , The result returned is NULL
LOG10(X) Return to 10 At the bottom of the X The logarithmic , When X <= 0 when , The result returned is NULL
LOG2(X) Return to 2 At the bottom of the X The logarithmic , When X <= 0 when , return NULL
mysql> SELECT POW(2,5),POWER(2,4),EXP(2),LN(10),LOG10(10),LOG2(4)
-> FROM DUAL;
+----------+------------+------------------+-------------------+-----------+---------+
| POW(2,5) | POWER(2,4) | EXP(2) | LN(10) | LOG10(10) | LOG2(4) |
+----------+------------+------------------+-------------------+-----------+---------+
| 32 | 16 | 7.38905609893065 | 2.302585092994046 | 1 | 2 |
+----------+------------+------------------+-------------------+-----------+---------+
1 row in set (0.00 sec)

2.5 Conversion between bases

function usage
BIN(x) return x Binary code of
HEX(x) return x Hexadecimal encoding
OCT(x) return x Octal encoding
CONV(x,f1,f2) return f1 The base number becomes f2 Hexadecimal number
mysql> SELECT BIN(10),HEX(10),OCT(10),CONV(10,2,8)
-> FROM DUAL;
+---------+---------+---------+--------------+
| BIN(10) | HEX(10) | OCT(10) | CONV(10,2,8) |
+---------+---------+---------+--------------+
| 1010 | A | 12 | 2 |
+---------+---------+---------+--------------+
1 row in set (0.00 sec)

3. String function

function usage
ASCII(S) Return string S Of the first character in ASCII Code value
CHAR_LENGTH(s) Return string s The number of characters . The functions and CHARACTER_LENGTH(s) identical
LENGTH(s) Return string s Bytes of , It's about character sets
CONCAT(s1,s2,…,sn) Connect s1,s2,…,sn For a string
CONCAT_WS(x,s1,s2,…,sn) Same as CONCAT(s1,s2,…) function , But add... Between each string x
INSERT(str, idx, len,replacestr) The string str From idx Position start ,len Substrings of characters long are replaced with strings replacestr
REPLACE(str, a, b) Use string b Replace string str All the strings that appear in a
UPPER(s) or UCASE(s) The string s All the letters of are converted to capital letters
LOWER(s) or LCASE(s) The string s All the letters of are converted to lowercase letters
LEFT(str,n) Return string str The leftmost n Characters
RIGHT(str,n) Return string str Far right n Characters
LPAD(str, len, pad) Use string pad Yes str Fill on the far left , until str The length of is len Characters
RPAD(str ,len, pad) Use string pad Yes str Fill on the far right , until str The length of is len Characters
LTRIM(s) Remove string s The space on the left
RTRIM(s) Remove string s The space on the right
TRIM(s) Remove string s Start and end spaces
TRIM(s1 FROM s) Remove string s The beginning and the end s1
TRIM(LEADING s1 FROM s) Remove string s At the beginning s1
TRIM(TRAILING s1 FROM s) Remove string s At the end s1
REPEAT(str, n) return str repeat n Results of
SPACE(n) return n A space
STRCMP(s1,s2) Compare strings s1,s2 Of ASCII The size of the code value
SUBSTR(s,index,len) Return from string s Of index Position it len Characters , The functions and SUBSTRING(s,n,len)、MID(s,n,len) identical
LOCATE(substr,str) Return string substr In string str The first place in , Act on POSITION(substr IN str)、INSTR(str,substr) identical . Not found , return 0
ELT(m,s1,s2,…,sn) Returns the string at the specified location , If m=1, Then return to s1, If m=2, Then return to s2, If m=n, Then return to sn
FIELD(s,s1,s2,…,sn) Return string s The position of the first occurrence in the string list
FIND_IN_SET(s1,s2) Return string s1 In string s2 Where in . among , character string s2 Is a comma separated string
REVERSE(s) return s The inverted string
NULLIF(value1,value2) Compare two strings , If value1 And value2 equal , Then return to NULL, Otherwise return to value1
 Be careful :MySQL in , The position of the string is from 1 At the beginning .

give an example :

mysql> SELECT FIELD('mm','hello','msm','amma'),FIND_IN_SET('mm','hello,mm,amma')
-> FROM DUAL;
+----------------------------------+-----------------------------------+
| FIELD('mm','hello','msm','amma') | FIND_IN_SET('mm','hello,mm,amma') |
+----------------------------------+-----------------------------------+
| 0 | 2 |
+----------------------------------+-----------------------------------+
1 row in set (0.00 sec)
mysql> SELECT NULLIF('mysql','mysql'),NULLIF('mysql', '');
+-------------------------+---------------------+
| NULLIF('mysql','mysql') | NULLIF('mysql', '') |
+-------------------------+---------------------+
| NULL | mysql |
+-------------------------+---------------------+
1 row in set (0.00 sec)

4. Date and time functions

4.1 Get date 、 Time

function usage
CURDATE() ,CURRENT_DATE() Return current date , Only years 、 month 、 Japan
CURTIME() , CURRENT_TIME() Return current time , When only 、 branch 、 second
NOW() / SYSDATE() / CURRENT_TIMESTAMP() / LOCALTIME() /
LOCALTIMESTAMP() Returns the current system date and time
UTC_DATE() return UTC( World standard time ) date
UTC_TIME() return UTC( World standard time ) Time

give an example


FROM DUAL;

4.2 Date and time stamp conversion

function usage
UNIX_TIMESTAMP() With UNIX Returns the current time in the form of a timestamp .SELECT UNIX_TIMESTAMP() ->1634348884
UNIX_TIMESTAMP(date) Time date With UNIX Return in the form of a timestamp .
FROM_UNIXTIME(timestamp) take UNIX The time of the timestamp is converted to the time of the normal format

give an example :

mysql> SELECT UNIX_TIMESTAMP(now());
+-----------------------+
| UNIX_TIMESTAMP(now()) |
+-----------------------+
| 1576380910 |
+-----------------------+
1 row in set (0.01 sec)
mysql> SELECT UNIX_TIMESTAMP(CURDATE());
+---------------------------+
| UNIX_TIMESTAMP(CURDATE()) |
+---------------------------+
| 1576339200 |
+---------------------------+
1 row in set (0.00 sec)
mysql> SELECT UNIX_TIMESTAMP(CURTIME());
+---------------------------+
| UNIX_TIMESTAMP(CURTIME()) |
+---------------------------+
| 1576380969 |
+---------------------------+
1 row in set (0.00 sec)
mysql> SELECT UNIX_TIMESTAMP('2011-11-11 11:11:11')
+---------------------------------------+
| UNIX_TIMESTAMP('2011-11-11 11:11:11') |
+---------------------------------------+
| 1320981071 |
+---------------------------------------+
1 row in set (0.00 sec)

| FROM_UNIXTIME(1576380910) |
+---------------------------+
| 2019-12-15 11:35:10 |
+---------------------------+
1 row in set (0.00 sec)

4.3 Get month 、 week 、 Weeks 、 Functions such as days

function usage
YEAR(date) / MONTH(date) / DAY(date) Return the specific date value
HOUR(time) / MINUTE(time) /
SECOND(time) Return specific time value
MONTHNAME(date) Return to the month :January,…
DAYNAME(date) Day of the week :MONDAY,TUESDAY…SUNDAY
WEEKDAY(date) What day of the week , Be careful , Zhou 1 yes 0, Zhou 2 yes 1,... Sunday is 6
QUARTER(date) Returns the quarter corresponding to the date , The scope is 1~4
WEEK(date) , WEEKOFYEAR(date) Go back to the week of the year
DAYOFYEAR(date) The return date is the day of the year
DAYOFMONTH(date) The return date is the day of the month
DAYOFWEEK(date) What day of the week , Be careful : Sunday is 1, Monday is 2,... Saturday is 7

give an example :

mysql> SELECT FROM_UNIXTIME(1576380910);
+---------------------------+
| FROM_UNIXTIME(1576380910) |
+---------------------------+
| 2019-12-15 11:35:10 |
+---------------------------+
1 row in set (0.00 sec)
SELECT YEAR(CURDATE()),MONTH(CURDATE()),DAY(CURDATE()),
HOUR(CURTIME()),MINUTE(NOW()),SECOND(SYSDATE())
FROM DUAL;

 Insert picture description here

SELECT MONTHNAME('2021-10-26'),DAYNAME('2021-10-26'),WEEKDAY('2021-10-26'),
QUARTER(CURDATE()),WEEK(CURDATE()),DAYOFYEAR(NOW()),
DAYOFMONTH(NOW()),DAYOFWEEK(NOW())
FROM DUAL;

 Insert picture description here

function usage
EXTRACT(type FROM date) Returns a specific part of a specified date ,type Specifies the value to be returned

EXTRACT(type FROM date) Function type The value and meaning of :

 Insert picture description here

SELECT EXTRACT(MINUTE FROM NOW()),EXTRACT( WEEK FROM NOW()),
EXTRACT( QUARTER FROM NOW()),EXTRACT( MINUTE_SECOND FROM NOW())
FROM DUAL;

4.5 Time and second conversion function

function usage
TIME_TO_SEC(time) take time Convert to seconds and return the result value . The conversion formula is : Hours 3600+ minute 60+ second
SEC_TO_TIME(seconds) take seconds The description is converted to include hours 、 Minutes and seconds
| TIME_TO_SEC(NOW()) |
+--------------------+
| 78774 |
+--------------------+
1 row in set (0.00 sec)
mysql> SELECT SEC_TO_TIME(78774);
+--------------------+
| SEC_TO_TIME(78774) |
+--------------------+
| 21:52:54 |
+--------------------+
1 row in set (0.12 sec)

4.6 A function that calculates the date and time

The first 1 Group :

function usage
DATE_ADD(datetime, INTERVAL expr type),ADDDATE(date,INTERVAL expr type) Returns the difference between the given date and time INTERVAL Date time of the time period
DATE_SUB(date,INTERVAL expr type),SUBDATE(date,INTERVAL expr type) Return and date Difference between INTERVAL The date of the interval

In the above functions type The value of :

 Insert picture description here
give an example :

ADDDATE('2021-10-21 23:32:12',INTERVAL 1 SECOND) AS col3,
DATE_ADD('2021-10-21 23:32:12',INTERVAL '1_1' MINUTE_SECOND) AS col4,
DATE_ADD(NOW(), INTERVAL -1 YEAR) AS col5, # It could be negative 
DATE_ADD(NOW(), INTERVAL '1_1' YEAR_MONTH) AS col6 # Need single quotes 
FROM DUAL;


SELECT DATE_SUB('2021-01-21',INTERVAL 31 DAY) AS col1,
SUBDATE('2021-01-21',INTERVAL 31 DAY) AS col2,
DATE_SUB('2021-01-21 02:01:01',INTERVAL '1 1' DAY_HOUR) AS col3
FROM DUAL;

The first 2 Group :

function usage
ADDTIME(time1,time2) return time1 add time2 Time for . When time2 When it is a number , It stands for seconds , Can be negative
SUBTIME(time1,time2) return time1 subtract time2 After time . When time2 When it is a number , It stands for second , Can be negative
DATEDIFF(date1,date2) return date1 - date2 Number of days between dates
TIMEDIFF(time1, time2) return time1 - time2 Time interval of
FROM_DAYS(N) Return from 0000 year 1 month 1 The date of ,N Days later
TO_DAYS(date) Return date date distance 0000 year 1 month 1 Days of the day
LAST_DAY(date) return date The date of the last day of the month
MAKEDATE(year,n) Returns a date for a given year and the number of days in the year
MAKETIME(hour,minute,second) Set the given hour 、 Minutes and seconds are combined into time and return
PERIOD_ADD(time,n) return time add n After time

give an example :

SELECT
ADDTIME(NOW(),20),SUBTIME(NOW(),30),SUBTIME(NOW(),'1:1:3'),DATEDIFF(NOW(),'2021-10- 01'),
TIMEDIFF(NOW(),'2021-10-25 22:10:10'),FROM_DAYS(366),TO_DAYS('0000-12-25'),
LAST_DAY(NOW()),MAKEDATE(YEAR(NOW()),12),MAKETIME(10,21,23),PERIOD_ADD(20200101010101,
10)
FROM DUAL;
mysql> SELECT ADDTIME(NOW(), 50);
+---------------------+
| ADDTIME(NOW(), 50) |
+---------------------+
| 2019-12-15 22:17:47 |
+---------------------+
1 row in set (0.00 sec)
+-------------------------+
| 2019-12-15 23:18:46 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT SUBTIME(NOW(), '1:1:1');
+-------------------------+
| SUBTIME(NOW(), '1:1:1') |
+-------------------------+
| 2019-12-15 21:23:50 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT SUBTIME(NOW(), '-1:-1:-1');
+----------------------------+
| SUBTIME(NOW(), '-1:-1:-1') |
+----------------------------+
| 2019-12-15 22:25:11 |
+----------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> SELECT FROM_DAYS(366);
+----------------+
| FROM_DAYS(366) |
+----------------+
| 0001-01-01 |
+----------------+
1 row in set (0.00 sec)
mysql> SELECT MAKEDATE(2020,1);
+------------------+
| MAKEDATE(2020,1) |
+------------------+
| 2020-01-01 |
+------------------+
1 row in set (0.00 sec)
mysql> SELECT MAKEDATE(2020,32);
+-------------------+
| MAKEDATE(2020,32) |
+-------------------+
| 2020-02-01 |
+-------------------+
1 row in set (0.00 sec)
mysql> SELECT MAKETIME(1,1,1);
+-----------------+
| MAKETIME(1,1,1) |
+-----------------+
| 01:01:01 |
+-----------------+
1 row in set (0.00 sec)
| PERIOD_ADD(20200101010101,1) |
+------------------------------+
| 20200101010102 |
+------------------------------+
1 row in set (0.00 sec)
mysql> SELECT TO_DAYS(NOW());
+----------------+
| TO_DAYS(NOW()) |
+----------------+
| 737773 |
+----------------+
1 row in set (0.00 sec)

give an example : Inquire about 7 How many new users are there in a day ?

SELECT COUNT(*) as num FROM new_user WHERE TO_DAYS(NOW())-TO_DAYS(regist_time)<=7

4.7 Formatting and parsing of dates

function usage
DATE_FORMAT(date,fmt) According to the string fmt Format date date value
TIME_FORMAT(time,fmt) According to the string fmt Format time time value
GET_FORMAT(date_type,format_type) Returns the display format of the date string
STR_TO_DATE(str, fmt) According to the string fmt Yes str To analyze , Resolve to a date

Above Not GET_FORMAT Function fmt Common format characters for parameters :

Formula symbol explain Formula symbol explain
%Y4 The number of digits indicates the year %y Two digits for the year
%M The name of the month means the month (January,…)%m Two figures indicate the month (01,02,03...)
%b Abbreviated month name (Jan.,Feb.,…)%c The number represents the month (1,2,3,…)
%D The English suffix indicates the number of days in the month (1st,2nd,3rd,…)%d Two figures indicate the number of days in the month (01,02…)
%e The number of days in the month (1,2,3,4,5…)
%H Two figures represent decimals ,24 hourly (01,02…)%h and %I Two figures represent hours ,12 hourly (01,02…)
%k Hours in digital form ,24 hourly (1,2,3)%l The number represents the hour ,12 hourly (1,2,3,4…)
%i Two figures represent minutes (00,01,02)%S and %s Two digits are seconds (00,01,02…)
%W The name of the week of the week (Sunday…)%a The abbreviation of a week (Sun.,Mon.,Tues.,…)
%w Number the days of the week (0=Sunday,1=Monday…)
%j With 3 The number of digits represents the number of days in the year (001,002…)%U Number the week of the year ,(1,2,3..) among Sunday For the first day of the week
%u Number the week of the year ,(1,2,3..) among Monday For the first day of the week
%T24 hourly %r12 hourly
%pAM or PM%% Express %

GET_FORMAT Function date_type and format_type The parameter values are as follows :
 Insert picture description here
give an example :

mysql> SELECT DATE_FORMAT(NOW(), '%H:%i:%s');
+--------------------------------+
| DATE_FORMAT(NOW(), '%H:%i:%s') |
+--------------------------------+
| 22:57:34 |
+--------------------------------+
1 row in set (0.00 sec)
SELECT STR_TO_DATE('09/01/2009','%m/%d/%Y')
FROM DUAL;
SELECT STR_TO_DATE('20140422154706','%Y%m%d%H%i%s')
FROM DUAL;
SELECT STR_TO_DATE('2014-04-22 15:47:06','%Y-%m-%d %H:%i:%s')
FROM DUAL;
SELECT STR_TO_DATE('09/01/2009','%m/%d/%Y')
FROM DUAL;
SELECT STR_TO_DATE('20140422154706','%Y%m%d%H%i%s')
FROM DUAL;
SELECT STR_TO_DATE('2014-04-22 15:47:06','%Y-%m-%d %H:%i:%s')
FROM DUAL;
mysql> SELECT STR_TO_DATE('2020-01-01 00:00:00','%Y-%m-%d');
+-----------------------------------------------+
| STR_TO_DATE('2020-01-01 00:00:00','%Y-%m-%d') |
+-----------------------------------------------+
| 2020-01-01 |
+-----------------------------------------------+
1 row in set, 1 warning (0.00 sec)

Process processing functions can be based on different conditions , Perform different processes , Can be in SQL Statement to implement different conditional choices .
MySQL The process processing functions in mainly include IF()、IFNULL() and CASE() function .

function usage
IF(value,value1,value2) If value The value of is TRUE, return value1, Otherwise return to value2
IFNULL(value1, value2) If value1 Not for NULL, return value1, Otherwise return to value2
CASE WHEN Conditions 1 THEN result 1 WHEN Conditions 2 THEN result 2… [ELSE resultn] END amount to Java Of if…else if…else…
CASE expr WHEN Constant values 1 THEN value 1 WHEN Constant values 1 THEN value 1 … [ELSE value n] END amount to Java Of switch…case…
SELECT IF(1 > 0,' correct ',' error ')
-> correct 
SELECT IFNULL(null,'Hello Word')
->Hello Word
SELECT CASE
WHEN 1 > 0
THEN '1 > 0'
WHEN 2 > 0
THEN '2 > 0'
ELSE '3 > 0'
END
->1 > 0
SELECT CASE 1
WHEN 1 THEN ' I am a 1'
WHEN 2 THEN ' I am a 2'
ELSE ' who are you '
SELECT employee_id,salary, CASE WHEN salary>=15000 THEN ' High salaries '
WHEN salary>=10000 THEN ' potential share '
WHEN salary>=8000 THEN ' Prick silk '
ELSE ' grassroots ' END " describe "
FROM employees;
SELECT oid,`status`, CASE `status` WHEN 1 THEN ' Unpaid '
WHEN 2 THEN ' Paid '
WHEN 3 THEN ' Shipped '
WHEN 4 THEN ' Confirm receipt '
ELSE ' Invalid order ' END
FROM t_order;
mysql> SELECT CASE WHEN 1 > 0 THEN 'yes' WHEN 1 <= 0 THEN 'no' ELSE 'unknown' END;
+---------------------------------------------------------------------+
| CASE WHEN 1 > 0 THEN 'yes' WHEN 1 <= 0 THEN 'no' ELSE 'unknown' END |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)


mysql> SELECT CASE WHEN 1 < 0 THEN 'yes' WHEN 1 = 0 THEN 'no' ELSE 'unknown' END;
+--------------------------------------------------------------------+
| CASE WHEN 1 < 0 THEN 'yes' WHEN 1 = 0 THEN 'no' ELSE 'unknown' END |
+--------------------------------------------------------------------+
| unknown |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT CASE 1 WHEN 0 THEN 0 WHEN 1 THEN 1 ELSE -1 END;
+------------------------------------------------+
| CASE 1 WHEN 0 THEN 0 WHEN 1 THEN 1 ELSE -1 END |
+------------------------------------------------+
| 1 |
+------------------------------------------------+
1 row in set (0.00 sec)



mysql> SELECT CASE -1 WHEN 0 THEN 0 WHEN 1 THEN 1 ELSE -1 END;
+-------------------------------------------------+
| CASE -1 WHEN 0 THEN 0 WHEN 1 THEN 1 ELSE -1 END |
+-------------------------------------------------+
| -1 |
+-------------------------------------------------+
1 row in set (0.00 sec)



SELECT employee_id,12 * salary * (1 + IFNULL(commission_pct,0))
FROM employees;



SELECT last_name, job_id, salary,
CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
WHEN 'ST_CLERK' THEN 1.15*salary
WHEN 'SA_REP' THEN 1.20*salary
ELSE salary END "REVISED_SALARY"
FROM employees;

 Insert picture description here

6. Encryption and decryption functions

The encryption and decryption function is mainly used to encrypt and decrypt the data in the database , To prevent data from being stolen by others . These functions are very useful in ensuring database security .

function usage
PASSWORD(str) Return string str The encrypted version of ,41 Bit long string . Encryption result Irreversible , Commonly used for user password encryption
MD5(str) Return string str Of md5 Encrypted value , It's also a form of encryption . If the parameter is NULL, Will return NULL
SHA(str) From the original plaintext password str Calculate and return the encrypted password string , When the parameter is NULL when , return NULL. SHA Encryption algorithm than MD5 More secure .
ENCODE(value,password_seed) Return to use password_seed Encrypt as an encryption password value
DECODE(value,password_seed) Return to use password_seed Decrypt as an encrypted password value

You can see ,ENCODE(value,password_seed) Function and DECODE(value,password_seed) Functions are inverse functions to each other .
give an example :

mysql> SELECT PASSWORD('mysql'), PASSWORD(NULL);
+-------------------------------------------+----------------+
| PASSWORD('mysql') | PASSWORD(NULL) |
+-------------------------------------------+----------------+
| *E74858DB86EBA20BC33D0AECAE8A8108C56B17FA | |
+-------------------------------------------+----------------+
1 row in set, 1 warning (0.00 sec)


SELECT md5('123')
->202cb962ac59075b964b07152d234b70


SELECT SHA('Tom123')
->c7c506980abc31cc390a2438c90861d0f1216d50


mysql> SELECT ENCODE('mysql', 'mysql');
+--------------------------+
| ENCODE('mysql', 'mysql') |
+--------------------------+
| íg ¼ ìÉ |
+--------------------------+
1 row in set, 1 warning (0.01 sec)


mysql> SELECT DECODE(ENCODE('mysql','mysql'),'mysql');
+-----------------------------------------+
| DECODE(ENCODE('mysql','mysql'),'mysql') |
+-----------------------------------------+
| mysql |
+-----------------------------------------+
1 row in set, 2 warnings (0.00 sec)

7. MySQL Information functions

MySQL There are some built-in functions that can be queried MySQL Functions of information , These functions are mainly used to help database developers or operation and maintenance personnel better maintain the database .

VERSION() Returns the current MySQL Version number of
CONNECTION_ID() Returns the current MySQL Number of connections to the server
DATABASE(),SCHEMA() return MySQL The database where the command line is currently located
USER(),CURRENT_USER()、SYSTEM_USER(),SESSION_USER() Return to the current connection MySQL Username , The format of the returned result is “ Host name @ user name ”
CHARSET(value) Return string value The character set of the argument
COLLATION(value) Return string value Comparison rules of

give an example :

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| test |
+------------+
1 row in set (0.00 sec)



mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| test |
+------------+
1 row in set (0.00 sec)



mysql> SELECT USER(), CURRENT_USER(), SYSTEM_USER(),SESSION_USER();
+----------------+----------------+----------------+----------------+
| USER() | CURRENT_USER() | SYSTEM_USER() | SESSION_USER() |
+----------------+----------------+----------------+----------------+
| root@localhost | root@localhost | root@localhost | root@localhost |
+----------------+----------------+----------------+----------------+



mysql> SELECT CHARSET('ABC');
+----------------+
| CHARSET('ABC') |
+----------------+
| utf8mb4 |
+----------------+
1 row in set (0.00 sec)




mysql> SELECT COLLATION('ABC');
+--------------------+
| COLLATION('ABC') |
+--------------------+
| utf8mb4_general_ci |
+--------------------+
1 row in set (0.00 sec)

MySQL There are some functions in that cannot be specifically classified , But these functions are MySQL In the process of development, operation and maintenance of
Of .

function usage
FORMAT(value,n) Returns a pair of numbers value Formatted result data .n Express rounding Keep it after the decimal point n position
CONV(value,from,to) take value The value of is converted between different hexadecimals
INET_ATON(ipvalue) Will be separated by dots IP The address is converted to a number
INET_NTOA(value) Put... In digital form IP The address is converted to dot separated IP Address
BENCHMARK(n,expr) Expression expr repeat n Time . Used for testing MySQL Handle expr The time taken by the expression
CONVERT(value USINGchar_code) take value The character encoding used is modified to char_code

give an example :

#  If n Is less than or equal to 0, Then only the integer part 
mysql> SELECT FORMAT(123.123, 2), FORMAT(123.523, 0), FORMAT(123.123, -2);
+--------------------+--------------------+---------------------+
| FORMAT(123.123, 2) | FORMAT(123.523, 0) | FORMAT(123.123, -2) |
+--------------------+--------------------+---------------------+
| 123.12 | 124 | 123 |
+--------------------+--------------------+---------------------+
1 row in set (0.00 sec)




mysql> SELECT CONV(16, 10, 2), CONV(8888,10,16), CONV(NULL, 10, 2);
+-----------------+------------------+-------------------+
| CONV(16, 10, 2) | CONV(8888,10,16) | CONV(NULL, 10, 2) |
+-----------------+------------------+-------------------+
| 10000 | 22B8 | NULL |
+-----------------+------------------+-------------------+
1 row in set (0.00 sec)



mysql> SELECT INET_ATON('192.168.1.100');
+----------------------------+
| INET_ATON('192.168.1.100') |
+----------------------------+
| 3232235876 |
+----------------------------+
1 row in set (0.00 sec)



#  With “192.168.1.100” For example , The calculation method is 192 multiply 256 Of 3 Power , add 168 multiply 256 Of 2 Power , add 1 multiply 256, Plus 100.
| INET_NTOA(3232235876) |
+-----------------------+
| 192.168.1.100 |
+-----------------------+
1 row in set (0.00 sec)



mysql> SELECT BENCHMARK(1, MD5('mysql'));
+----------------------------+
| BENCHMARK(1, MD5('mysql')) |
+----------------------------+
| 0 |
+----------------------------+
1 row in set (0.00 sec)



mysql> SELECT BENCHMARK(1000000, MD5('mysql'));
+----------------------------------+
| BENCHMARK(1000000, MD5('mysql')) |
+----------------------------------+
| 0 |
+----------------------------------+
1 row in set (0.20 sec)



mysql> SELECT CHARSET('mysql'), CHARSET(CONVERT('mysql' USING 'utf8'));
+------------------+----------------------------------------+
| CHARSET('mysql') | CHARSET(CONVERT('mysql' USING 'utf8')) |
+------------------+----------------------------------------+
| utf8mb4 | utf8 |
+------------------+----------------------------------------+
1 row in set, 1 warning (0.00 sec)

To be continued ;

原网站

版权声明
本文为[if you never leave me, i will be with you till death do us apart]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211908429591.html