MySQL Basics 1

1. Front

1.1 SQL classification

category meaning
DDL (Data Definition Language): Data Definition Language Used to create and modify databases and tables, such as create, drop, alter, etc.
DML (Data Manipulation Language): data manipulation language Used to insert, modify, and query records in the table, such as insert, delete, update, select, etc.
DCL (Data Control Language): Data Control Language Used to define databases, tables, fields, user access rights, and security levels, such as commit, rollback, grant, revoke, savepoint, etc.

in

  • Select is the most commonly used statement, and it can also be regarded as a separate category: DQL (Data Query Language), that is, data query language;
  • Commit and rollback are related to transactions, which can be regarded as a category: TCL (Transaction Control Language), which is a transaction control language;

1.2 SQL usage specification

insert image description here

1.3 Naming rules

  • Custom name, the value range is uppercase and lowercase letters az, AZ, numbers 0-9, and underscore _;
  • A custom name composed of multiple words can be separated by underscores;

insert image description here

1.4 SQL case specification

In short, use lowercase for custom names, and use uppercase for things provided by SQL;
insert image description here

1.5 Notes

  • Single-line comment: 1) MySQL unique: # comment content; 2) -- comment content;
  • Multi-line comment: /* comment content */;

1.6 Execute SQL file

  • Method 1: Enter the mysql environment in the command line mode, and use the command source 指定SQL文件的具体路径to execute the corresponding SQL file;
  • Method 2: It can be used in graphical tools such as Navicat 工具->执行SQL文件->选择指定的SQL文件;

2. SELECT statement

2.1 Basic structure:

SELECT 字段1,字段2... 
FROM 表名;

2.2 Add an alias AS for the field

  • Among them, AS means the alias Alias, which can be omitted, but it is not recommended to omit it;
  • If you use multiple words as an alias and use spaces to separate them, you can use double quotes to enclose the alias;
SELECT 字段1 AS 别名1,字段2 AS 别名2... 
FROM 表名;

2.3 Deduplication of query results DISTINCT

  • The essence of DISTINCT is to deduplicate the combination of query columns, and only when the values ​​of all columns of some records are the same, they are regarded as duplicate records;
SELECT DISTINCT 字段1 AS 别名1,字段2 AS 别名2... 
FROM 表名;

2.4 Null value participates in operation NULL

  • Empty value is NULL;
  • NULL is not 0, '', 'NULL';
  • Null values ​​participate in the operation, and the result is NULL;

2.5 Query constants

as follows:

SELECRT 1,salary 
FROM employees;

A constant field will be added to each record;

2.6 Display table structure

DESCRIBE 表名;

or

DESC 表名;

2.7 Condition query/filter data WHERE

  • Only display relevant records that meet the query conditions;
  • The statement is after the FROM structure and immediately after the FROM;
  • The alias of the query field cannot be used to set the filter condition;
SELECT DISTINCT 字段1 AS 别名1,字段2 AS 别名2... 
FROM 表名 
WHERE 过滤条件;

3. Operators

3.1 Arithmetic operators

  • Addition, subtraction, multiplication, division and remainder operations: +, -, *, / or div, % or mod;
  • In SQL, the + sign only has the function of addition. When operating with a string, the string will be implicitly converted into a value. The premise of conversion is that the content of the string is composed of numbers, such as "123". If the string content is a character, treat it as 0 ;
  • When performing division, 1) when the denominator is non-zero, the result must be a floating point type ; 2) when the denominator is 0, the result is NULL ;
  • The sign of the modulo operation result is consistent with the modulus ;
  • The results of NULL participating in the operation are all NULL;
    insert image description here

3.2 Comparison Operators

  • Returns 1 if the comparison is true, 0 if false, and NULL otherwise ;
  • Except for the safe equal operator <=>, other operators that have NULL involved in the operation result are all NULL;
  • In the equal operator <=>, if one of the operands is NULL, the result is 0, and if both operands are NULL, the result is 1;
    insert image description here
  • The following are non -symbolic operators :
    1) BETWEEN...AND... search interval is left-closed and right-closed ;
    2) IN or NOT IN is searched in a discrete set
    ; 3) LIKE is used for fuzzy query, you can use 1) underscore_ : Indicates a character; 2) Percent sign %: Indicates an unknown number of characters; 3) Slash \: Indicates escape, special characters are escaped to make them appear as ordinary characters; complete specific query functions ;
    insert image description here

3.3 Logical operators

  • The returned results are 0, 1, and NULL;
  • NULL participates in the operation and the result is NULL;
    insert image description here

3.4 Bitwise operators

  • Converting operands to binary for operation can improve efficiency to a certain extent;
  • Within a certain range, shifting one bit to the left is equivalent to multiplying by 2, and shifting one bit to the right is equivalent to dividing by 2;
    insert image description here

3.5 Operator precedence

  • Brackets have the highest priority, so when writing SQL, which part you want to calculate first, just use brackets to wrap it;
    insert image description here

4. Sorting and paging

4.1 Sorting ORDER BY

  • Declared after the FROM structure;
  • When sorting is not used, the default query results are displayed in the order of data insertion;
  • ASC (by default, can not be specified) means ascending order, DESC means descending order;
  • You can use the alias of the query field to specify the sorting method;
  • The sort field may not be in the query field;
  • Multi-level sorting can be used, starting from the first level of sorting;
SELECT DISTINCT 字段1 AS 别名1,字段2 AS 别名2... 
FROM 表名 
WHERE 过滤条件
ORDER BY 字段1 排序方式1,字段2 排序方式2...;

insert image description here

4.2 Paging LIMIT OFFSET

  • After the declaration of the FROM structure, it must be declared at the end of the entire SELECT structure ;
  • The position offset starts from 0, if the offset is 0, you can directly use the number of LIMIT entries for pagination query;
  • Pagination query formula: LIMIT (number of pages - 1) * page size, page size ;
  • Constraining the number of returned results can reduce the network transmission volume of the data table, and can also improve query efficiency;
  • Use the LIMIT keyword in MySQL, PostgreSQL, MariaDB and SQLite, and it needs to be placed at the end of the SELECT statement;
SELECT DISTINCT 字段1 AS 别名1,字段2 AS 别名2... 
FROM 表名 
WHERE 过滤条件
ORDER BY 字段1 排序方式1,字段2 排序方式2...
LIMIT 位置偏移量,条目数;

or

SELECT DISTINCT 字段1 AS 别名1,字段2 AS 别名2... 
FROM 表名 
WHERE 过滤条件
ORDER BY 字段1 排序方式1,字段2 排序方式2...
LIMIT 条目数 OFFSET 位置偏移量;

5. Multi-table query/joint query

5.1 Why do we need multi-table query

  • Alleviate the problem of single-table data redundancy;
  • Reduce IO times and improve query efficiency;
  • Improve multi-user query concurrency;

5.2 How to perform multi-table query

When performing multi-table queries, you need to pay attention to the following points:

  • The connection conditions between multiple tables need to be declared in the WHERE structure;
  • If the join condition is omitted or invalid, a Cartesian product error will result;
  • Cartesian product is also called cross connection CROSS JOIN;
  • If the field to be queried exists in multiple tables, you need to explicitly indicate the specific table where the field is located;
  • When querying multiple tables, it is recommended to explicitly specify tables for all query fields;
  • For the simplicity of SQL, an alias can be specified for the table. Once the alias is specified, the alias of the table must be used in other parts (SELECT, WHERE, etc.), instead of the original name of the table;
  • If there are N tables for multi-table query, at least N-1 join conditions are required ;
  • It is necessary to control the number of connection tables, too many connection tables will reduce query efficiency;

5.3 Classification of multi-table queries

Only the classification angle is different:

  • Angle 1: Equivalent connection VS non-equivalent connection, that is, whether the connection condition is an equal judgment;
  • Angle 2: Self-join VS non-self-join, whether multiple tables can be regarded as a copy of a single table;
  • Angle 3: Inner join VS Outer join
    Inner join : Merge the rows of two or more tables with the same column, the result set does not contain rows that do not match one table with another table ;
    Outer join : Two tables are in the process of joining except In addition to returning the rows that meet the join conditions, the rows that do not meet the conditions in the left (or right) table are returned. This kind of connection is called a left (or right) outer join . When there are no matching rows, the corresponding column in the result table is empty (NULL) .
    If it is a left outer join , the table on the left in the join condition is also called the main table , and the table on the right is called the slave table .
    If it is a right outer join , the table on the right in the join condition is also called the main table , and the table on the left is called the slave table .
    If the unmatched rows in both tables are displayed, it is called a full outer join ;

5.3.1 Realization of inner join, outer join and full outer join

SQL92 standard:

  • In the SQL92 standard, there are only left outer joins and right outer joins, and there is no implementation of full outer joins;
  • MySQL does not support the implementation of the SQL92 standard for outer joins;
  • In SQL92, (+) is used to mark the location of the slave table, indicating which is the slave table in the outer join, for example, xxx=yyy(+) means that the table where yyy is located is the slave table;

SQL99 standard : use JOIN...ON to realize multi-table query;

5.3.2 SQL99 standard realizes multi-table query

Basic template:

SELECT table1.column, table2.column,table3.column
FROM table1
JOIN table2 ON table1 和 table2 的连接条件
JOIN table3 ON table2 和 table3 的连接条件
  • The meaning of the keywords JOIN, INNER JOIN, and CROSS JOIN is the same, and they all represent inner connections;
  • Left outer connection: LEFT OUTER JOIN; Right outer connection: RIGHT OUTER JOIN;
  • Full outer connection: FULL JOIN or FULL OUTER JOIN;
  • MySQL does not support FULL JOIN or FULL OUTER JOIN, you can use LEFT JOIN UNION RIGHT JOIN instead;

5.3.3 7 implementations of SQL JOIN

  • UNION and UNION ALL can realize the merging of multiple SELECT result sets;
  • The difference between the two is that UNION will deduplicate the result set, and the resource consumption is relatively large;

insert image description here

References:

  • Silicon Valley

core:

  • It is necessary to understand the execution order of different components in the entire SELECT structure;
  • Multi-table query JOIN...ON..., 7 implementations of SQL JOIN;

Guess you like

Origin blog.csdn.net/qq_43665602/article/details/130365507