MySQL Basics 2

1. Function

  • The use of functions can improve code efficiency and code maintainability;
  • Different DBMSs have their own unique functions, so you need to pay special attention when using functions, which leads to poor portability of SQL using functions;
  • Functions are divided into built-in functions and custom functions;
  • Built-in functions include numeric functions, string functions, date and time functions, process control functions, encryption and decryption functions, functions for obtaining MySQL information, aggregation functions, etc., which can be further divided into single-row functions, aggregation functions (or grouping functions ) ;

insert image description here

1.1 One-line functions

  • manipulate data objects;
  • accepts parameters and returns a result;
  • Transform only one row ;
  • returns one result per row ;
  • can be nested;
  • The parameter can be a column or a value;

1.1.1 Numeric functions

  • Basic functions:
  • The interval generated by the RAND function is [0,1) left-closed and right-open interval;
    insert image description here
  • Conversion between degrees and radians:
    insert image description here
  • Trigonometric functions:

insert image description here

  • Exponential function, logarithmic function:
    insert image description here
  • Conversion between bases:
    insert image description here

1.1.2 String functions

  • The string index subscript in MySQL starts from 1 ;

insert image description here

  • The STRCMP function compares the size of two strings. If s1>s2, it returns 1, otherwise it returns -1, and if the two are equal, it returns 0;
  • If substr does not exist in str, the LOCATE function returns 0;
    insert image description here
    insert image description here

1.1.3 Date and time functions

  • Get date and time:
    insert image description here

  • Conversion of date and timestamp:
    insert image description here

  • Functions to get the month, week, week number, day number, etc.:
    insert image description here

  • Date manipulation functions:

insert image description here

  • Functions for time and seconds conversion:
    insert image description here
  • Functions to calculate dates and times:
    insert image description here
    insert image description here
    insert image description here
  • Formatting and parsing of dates: The values ​​of the date_type and format_type parameters
    insert image description here
    insert image description here
    insert image description here
    in the GET_FORMAT function are as follows:
    insert image description here

1.1.4 Process control function

  • In the CASE function, the ELSE structure is optional and may not be written;
    insert image description here
/*练习:查询部门号为 10,20, 30 的员工信息, 若部门号为 10, 则打印其工资的 1.1 倍, 20 号部门, 则打印其
工资的 1.2 倍, 30 号部门打印其工资的 1.3 倍数。*/
# 流程控制函数
SELECT *,CASE department_id
				WHEN 10 THEN salary*1.1
				WHEN 20 THEN salary*1.2
				WHEN 30 THEN salary*1.3
				END total_salary
FROM employees
WHERE department_id IN (10,20,30);

1.1.5 Encryption and decryption functions

  • PASSWORD, ENCODE/DECODE functions have been deprecated in MySQL8.0;
  • The encryption work can be realized at the back end, and the encrypted data is stored in the database without storing the data in the database and then encrypting;
    insert image description here

1.1.6 Information function

  • CONNECTION_ID() represents a unique connection ID;

insert image description here

1.1.7 Other functions

  • The FORMAT function plays a similar role to the ROUND function, the difference is that if the value of n is less than or equal to 0, only the integer part is reserved;
  • When performing IP address conversion, when expressing an IPv4 address in dotted decimal, each value ranges from 0 to 255, a total of 256, so each position can be regarded as a power of 0, 1, 2, 3 from right to left, When converting it to an integer, you can use the exponential function with a base of 256 to calculate: take "192.168.1.100" as an example, the calculation method is 192 times 256 to the 3rd power, plus 168 times 256 to the 2nd power, plus Multiply 1 by 256 and add 100;

insert image description here

1.2 Aggregate function/group function

  • Aggregate functions act on a set of data and return a value for a set of data ;
  • Aggregate functions cannot be nested . For example, calls in the form of "AVG(SUM(field name))" cannot appear;

insert image description here

1.2.1 Common aggregate functions

  • SUM and AVG are only applicable to numeric types and will automatically filter NULL values;
  • MAX and MIN are suitable for numeric types, string types, and date and time types, and will automatically filter NULL values;
  • COUNT is applicable to any type and is used to count the number of specified fields in the query results (only the specified field is not empty):
    1) COUNT(*), COUNT(1), COUNT (specified field) can be used to count the conditions met The number of records, but the method of COUNT (specified field) may be wrong, because this method only counts the case where the field is not empty;
    insert image description here
    insert image description here

insert image description here

  • Formula: AVG=SUM/COUNT;

1.2.2 GROUP BY for grouping

SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
  • The data in the table can be divided into several groups using the GROUP BY clause;
  • All columns in the SELECT list not included in the group function should be included in the GROUP BY clause;
  • Columns included in the GROUP BY clause do not have to be included in the SELECT list;
  • Statement after FROM, before ORDER BY;
  • You can use WITH ROLLUP in GROUP BY, which means adding a record after all the grouped records queried, which calculates the overall situation of all the queried records; when using ROLLUP, you cannot use the ORDER BY clause to sort the results at the same time , ie ROLLUP and ORDER BY are mutually exclusive.

1.2.3 HAVING for conditional filtering

SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING condition]
[ORDER BY column];
  • The statement is after the GROUP BY;
  • It is recommended to use it with GROUP BY;
  • When the filter condition does not involve an aggregate function, use WHERE; when the filter condition involves an aggregate function, use HAVING;

1.2.4 HAVING与WHERE

insert image description here

2. The complete structure of SQL and the underlying execution process

2.1 Complete structure of query statement

SELECT ...,....,...
FROM ... JOIN ...
ON 多表的连接条件
JOIN ...
ON ...
WHERE 不包含组函数的过滤条件
AND/OR 不包含组函数的过滤条件
GROUP BY ...,...
HAVING 包含组函数的过滤条件
ORDER BY ... ASC/DESC
LIMIT ...,...
#其中:
#(1)from:从哪些表中筛选
#(2)on:关联多表查询时,去除笛卡尔积
#(3)where:从表中筛选的条件
#(4)group by:分组依据
#(5)having:在统计结果中再次筛选
#(6)order by:排序
#(7)limit:分页

2.2 Execution process

insert image description here

3. Subqueries

insert image description here

  • It can also be called a nested query, which refers to a query in which one query statement is nested inside another query statement;

  • The use of subqueries in SQL greatly enhances the ability of SELECT queries, because many times queries need to obtain data from the result set, or need to calculate a data result from the same table first, and then compare this data result (maybe a certain scalar, and possibly a collection) for comparison;

  • The subquery (inner query) is executed once before the main query;

  • The result of the subquery is used by the main query (outer query);

  • Notes:
    1) Subqueries should be included in parentheses ;
    2) Place subqueries on the right side of comparison conditions ;
    3) Single-row operators correspond to single-row subqueries, and multi-row operators correspond to multi-row subqueries ;

  • From-type subquery: The subquery is part of from, and the subquery should be quoted with (), and an alias should be given to the subquery
    , and it should be used as a "temporary virtual table".

  • Subqueries can be used not only in SELECT structures, but also in update and delete operations;

3.1 Subquery classification

  • According to whether one or more records are returned according to the result of the inner query, subqueries are divided into single-row subqueries and multi-row subqueries ;
  • According to whether the inner query is executed multiple times, the subquery is divided into correlated (or correlated) subqueries and uncorrelated (or non-correlated) subqueries ;

3.1.1 Single row subqueries

Single row comparison operators :
insert image description here

3.1.2 Multi-row subqueries

  • Also known as a set comparison subquery;
  • Inner query returns multiple rows;
  • Using multi-line comparison operators;
  • ANY means that it only needs to compare with one of them to meet the conditions, and ALL means to compare with all values ​​and meet the conditions ;

insert image description here

3.1.3 Correlated subqueries

insert image description here

  • The inner query is related to the main query. Each execution of the inner query needs the information passed in from the main query, and the columns in the main query are used in the subquery;
  • The inner query is executed multiple times, and each time the outer query is executed, the subquery must be recalculated;
  • Correlated subqueries are executed row by row, and the subquery is executed once for each row of the main query;
    insert image description here
  • In the complete SELECT structure, except for GROUP BY and LIMIT, subqueries can be used in other positions ;

3.1.3.1 EXISTS and NOT EXISTS keywords

  • Correlative subqueries are usually used together with the EXISTS operator to check whether there are rows satisfying the condition in the subquery ; 1) If there is no row satisfying the condition
    in the subquery : the condition returns FALSE; continue in the subquery 2 ) If there are rows satisfying the condition in the subquery : do not continue to search in the subquery; the condition returns TRUE;
  • The NOT EXISTS keyword means that if a certain condition does not exist, it returns TRUE, otherwise it returns FALSE;

like:

# 查询公司管理者的employee_id,last_name,job_id,department_id信息
select e.employee_id,e.last_name,e.job_id,e.department_id
from employees e
where exists (
	select manager_id
    from employees e2
    where e2.manager_id=e.employee_id
);

# 查询departments表中,不存在于employees表中的部门的department_id和department_name
select department_id,department_name
from departments d
where not exists (
	select *
    from employees e
    where e.department_id=d.department_id
);

core content:

  • Single-line functions: numeric functions: basic functions; string functions; date and time functions;
  • aggregate function;
  • SQL complete structure and execution process;
  • subquery ;

source:

  • Silicon Valley

Supongo que te gusta

Origin blog.csdn.net/qq_43665602/article/details/130450374
Recomendado
Clasificación