Common advanced use of mysql database

  1. Transaction
    1) The unit of work in mysql is composed of one or more sql statements. "If you fail to succeed, you will be benevolent." Either all of them are executed successfully or all of them fail to ensure data consistency.
    2) Transaction rollback: If any SQL execution fails in the transaction, ROLLBACK can roll back the transaction, restore the data to the state before the transaction is executed, and ensure data consistency.
    3) Premise: mysql storage engine InnoDB
    4) Transaction characteristics: ACID
    atomic ATOMICITY
    transaction SQL statements are indivisible, either all succeed or all fail.
    Consistency CONSISTENCY
    Regardless of whether the transaction succeeds or fails, the data is always consistent.
    Isolation ISOLATION
    transactions and transactions are isolated from each other and do not affect each other. Once a
    persistent DURABLITY
    transaction is submitted successfully, the changes to the data are persistent, and the transaction cannot be rolled back.
    5)
    Commitment of the transaction Commit transaction displayed by COMMIT.
    Implicit commit of transaction DDL, DCL, etc. can cause implicit commit of transaction.
    6) The operation of the transaction
    BEGIN
    COMMIT
    ROLLBACK
    SAVEPOINT
    7) The automatic commit mode
    of the transaction The transaction in mysql is automatically committed, that is, the COMMIT statement is added by default after each SQL statement.
    View the automatic transaction commit mode of mysql:
SHOW VARIABLES  LIKE 'autocommit'

Modify the automatic submission mode of mysql

SET AUTOCOMMIT=1   表示开启
SET AUTOCOMMIT=0   表示关闭
  1. DQL
    SELECT statement to query the records in the table
    1) Simple query
SELECT 字段1,字段2,....,字段n  FROM 表名  WHERE子句

Among them:
If you query all the fields in the table, you can use the wildcard * to indicate.
An alias can be added after the field: the field AS alias, AS can be omitted, generally omitted.
The table name can also use AS to specify the alias.

2) Use operators to process the query field (does not affect the original data in the table)

+ - * /
SELECT ename, sal+2000 'salary',hiredate FROM emp 查询的工资每人增加2000

3) NULL value
null is not a value of 0, nor is it the maximum value, nor is it the minimum value. It is an indeterminate value.
The result of null participating in arithmetic operation is still null.
If you want null to participate in the calculation, you can specify a default value for null, participate in transportation, and use COALESCE.

SELECT ename, COALESCE(sal,0)+2000  'salary',hiredate FROM emp

4) Remove duplicate records DISTINCT

SELECT   DISTINCT 字段名  FROMWHERE子句
  1. Fuzzy query
    1) LIKE is used for fuzzy query of string fields
    2) The position where this symbol appears can be replaced by any number of characters
WHERE ename  LIKE '王%' 查询姓王的员工

3) The position where the symbol appears must have one and only one character.

WHERE ename  LIKE '王_' 比如查询全名为两个字的王姓员工(比如“王菲”)
  1. Sorting ORDER BY
    1) Sorting refers to sorting the query result set according to certain rules (ascending or descending)
    2) ASC ascending (default) DESC descending
    3) Syntax:
ELECT子句 ORDER BY 字段 ASC/DESC

Among them:
The clause of ORDER BY must be placed after the where clause.
If there is a null value in the sorted field, if it is sorted in ascending order, the record of the null value is at the top, and in descending order, null is at the end.
Date sorting, the earlier date is considered as a small value, and the later date is considered as a large value.
The string is sorted, sorted according to A~Z.
Chinese characters are sorted according to the dictionary order. If it is not gbk encoding, you need to use the convert function to convert it.

SELECT * FROM emp ORDER BY CONVERT(ename USING gbk) DESC

You can also sort by multiple fields

SELECT子句 ORDER BY 字段1 ASC/DESC, 字段2 ASC/DESC
  1. Limit the number of result sets returned by query
    1) Application scenario: Paging query
    2) Syntax:
SELECT子句  LIMIT  n  n表示获取结果集的前n条记录
SELECT子句   LIMIT   index, length 表示从结果集的第index处开始,取length条记录。index0表示从第一条记录。
  1. The
    powerful and easy-to-use functions provided in the function mysql improve the query and operation of developers in data management.

    Syntax: function name (parameter list)

Classification of commonly used functions
1) Mathematical function
ABS(x) returns the absolute value of x
SQRT(x) Square root
PI() Pi
MOD(x,y) Find the remainder of x divided by y

MOD(4.5,3)   结果是1.5

CEIL(x) returns the smallest integer greater than or equal to x

CEIL(3)  返回3
CEIL(3.3)  返回4

Application scenarios: scenarios where less than 1 is calculated by 1

FLOOR(x) returns the largest integer less than or equal to x

FLOOR(3)    3
FLOOR(3.4)  3
FLOOR(-3.4)   -4

Application scenario: Less than 1 discarded scenario

ROUND(x,y) reserves y decimal places and rounds up.

ROUND(23.55,1) 23.6
ROUND(23.55,-1)   20     -1表示保留到十位数

TRUNCATE(x,y) keep the decimal place y, the following truncation is discarded, no rounding

RAND() generates random numbers
Application scenario:
Random sorting: For example, 100 test questions are randomly selected from the question bank table

SELECT * FROM  题库表  ORDER BY  RAND()   LIMIT 100

POW(x,y) x to the power of y

Trigonometric function

2) String function
CONCAT(str1,str2,…) String splicing
LOWER(str) / LCASE(str) all converted to lowercase letters
UPPER(str) / UCASE(str) all converted to uppercase letters
LEFT(str,n) / RIGHT(str,n) Return the substring with length n on the left/right side
TRIM(str) Remove the spaces at the beginning and end of the string
SUBSTRING(str,index,length)
REVERSE(str)

3) Date and time
CURDATE() / CURRENT_DATE() Current date
NOW() Current year, month, day, hour, minute and second
CURRENT_TIMESTAMP() Current timestamp
DATE_ADD(hiredate, interval 10 DAY) Entry date plus ten days
DATE_SUB
DATE_FORMAT(date, fmt)

SELECT DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%s') FROM DUAL

4) Process function
CASE
CASE value WHEN expression THEN result
ELSE result
END

CASE WHEN sal>=3000  THEN '高收入'
ELSE '低收入'
END  'level'

IF
IF (expression 1, expression 2, expression 3)
If the value of expression 1 is true, it returns the value of expression 2, otherwise it returns the value of expression 3.

IFNULL
IFNULL (expression 1, expression 2)
if expression 1 is not null, return the value of expression 1, otherwise return the value of expression 2
NULLIF
NULLIF (expression 1, expression 2)
if expression 1 = expression Equation 2, then return null, otherwise return the value of expression 1

5) Other functions
VERSION()
USER()
DATABASE()

  1. Three paradigms
    1) The first paradigm
    The fields in the table are designed to be atomic and cannot be divided. (Depending on the specific scenario)
    2) In the second normal
    form, the table has a primary key as a unique identifier, and other fields depend on the primary key.
    (The second normal form is to split the table)
    3) The third normal form
    prohibits transitive dependence A->B->C

  2. Multi-table joint check
    1) The root cause of multi-table joint check: The
    design of the database follows three paradigms, and the relevant data is stored in multiple tables.
    2) Cartesian product Cartesian product of
    two tables, take the employee table and the department table as examples

SELECT * FROM1,2

The meaning of the Cartesian product: all possible combinations of recruits and recruiting departments.
The intermediate result set in the process of table joint investigation.
3) Equivalent query
SELECT Table 1. Field 1, Table 1. Field 2, Table 2. Field 1, Table 2. Field 2 FROM Table 1, Table 2 WHERE join conditions

SELECT e.empno, e.ename,d.dname,d.loc  FROM emp  e,dept d  WHERE  e.deptno=d.deptno

Connection conditions for n tables n -1
4) Non-equivalent connection
There is no common field between the multiple tables to be queried as the condition for the equivalence connection.
Query the employee's name, salary and salary grade. (There is no same field between the employee information table and the salary grade table, but the employee’s salary can be used to judge the interval that meets the grade in the salary grade table)
5) Self-join query
self-join query (see it as Join two identical tables for query)
query the names of employees and their supervisors

SELECT e1.ename '员工名',e2.ename '主管名' FROM emp e1,emp e2 WHERE e1.mgr=e2.empno
  1. SQL 99
    1) Cartesian product CROSS JOIN
SELECT * FROM1 CROSS JOIN2

2) Natural connection NATURAL JOIN
premise: the two tables have the same field as the connection condition
SELECT field FROM table 1 NATURAL JOIN table 2

SELECT e.ename,d.dname FROM emp e  NATURAL  JOIN dept d

You can use USING to specify the field of the connection condition, but remove NATURAL

SELECT e.ename,d.dname FROM emp e  JOIN dept d USING(deptno)

3) ON clause
When using the JOIN keyword, you can use the ON clause to specify the connection conditions.

4) Left join LEFT JOIN
takes the table on the left side of join as the main table, and the table on the right as the slave table. Regardless of whether the records of the master table can find matching records in the slave table or not, all records in the master table are displayed, and there is no match The field shows null.

5) Right join query RIGHT JOIN is the
same as left join query, with the table on the right as the master table and the table on the left as the slave table.

  1. Grouping function
    MAX() / MIN() returns the maximum and minimum values
    SUM() returns the sum
    AVG() returns the average value
    COUNT() returns the number of records
SELECT COUNT(*) FROM emp 查询员工的总数

Note: The grouping function excludes NULL values

  1. DISTINCT removes duplicate records of query results
SELECT DISTINCT deptno FROM emp 从员工信息表中查询部门编号
SELECT COUNT(DISTINCT deptno) FROM emp 查询员工表中有员工的部门的个数
  1. Grouping query
    1) Syntax
    SELECT clause GROUP BY field 1, field n
    where: The field following
    select must be included in the grouping field of group by, otherwise it is meaningless.
    If the group function is used after select, the field of the parameter of the group function may not be the field after groupby.
SELECT deptno,AVG(sal) FROM emp GROUP BY deptno 求员工表中的各部门的平均工资
SELECT deptno,job,AVG(sal) FROM emp GROUP BY deptno,job 求每个部门每个岗位的员工的平均工资

2) HAVING clause filtering the results after grouping

SELECT子句 FROMGROUP BY 字段 HAVING子句

The HAVING clause is to filter the results that have been divided into groups.
Generally, a grouping function is used in the having clause for filtering and conditional judgment.
Data after grouping cannot be filtered by where. (WHERE appears before GROUP BY)
3) GROUP BY uses the difference between where and having in
grouping queries The select statement of grouping queries can contain both where and having clauses.
where is before group by, and having is after group by.
Where limits the data before grouping, and having limits the data after grouping.

  1. Subquery
    1)
    When the query data needs to use the result of another query, a subquery is required.
    A subquery refers to a select statement, and the embedded select statement is called a subquery or an internal query.
    Parentheses are generally used to enclose sub-query statements.
    (Tips: Generally, you can first treat the parentheses as a constant, build the frame, and then add the parentheses)
    Subqueries can be used in the where clause, after from, and after having.
SELECT ename,sal FROM emp WHERE sal=(SELECT MIN(sal) FROM emp) 查询最低工资的员工姓名和工资

2) Single-row subquery The
return result is one row and one column (that is, a value)
= !=> <>= <=

3) Multi-row
subquery If the result of the subquery returns multiple rows of
IN, it is sufficient to match one of the returned values.
ANY matches one of the results of the subquery.
>ANY means greater than the minimum value in the result
<ANY means less than the maximum value in the result
=ANY is equivalent to IN
ALL and any of the results returned by the subquery
>ALL means greater than the maximum value of the returned result
<ALL Less than the minimum value of the result
= ALL is equal to all values, meaningless.
Note: If the result of the subquery has a null value, NOT IN is not used

4) The subquery is used after FROM,
the result of the subquery is treated as a temporary table

Source: Neusoft Java Training

Guess you like

Origin blog.csdn.net/weixin_44997802/article/details/108614443