[Front-end operation and maintenance] Open up the two channels of Ren and Du! (No nonsense version of mysql command)

ORM

Some students who don't know ORM can understand that it is equivalent to using low code to build an interface. Low code is a more abstract tool to do js, ​​html and css. Here, it means more abstract tools to do mysql native things.

Some people will say that I use ORM to write SQL when using nodejs. I don’t need to learn native SQL. This is completely wrong. You can go to its github to see the ORM tool. There are many issues that it has not solved. This kind of thing you If you don’t know native SQL, it’s very difficult to troubleshoot problems first. Then you find out, do you wait for others to fix the issue before going online?

There are also slightly more complicated joint tables, and the performance of SQL written by ORM is poor.

Classification and characteristics of SOL statements

At the beginning, I didn’t pay much attention to this classification and characteristics. Later, I became confused when learning SQL. I felt that it would be easier to memorize SQL statements after having classification.

SQL language is divided into four categories: Data Query Language (DQL), Data Manipulation Language (DML), Data Definition Language (DDL) and Data Control Language (DCL).

You see, these are all DxL, only the x in the middle is different. D refers to Data, which means data, and L refers to Language.

DQL

So let’s look at DQL first. Q refers to query. Query

Our common SELECT, FORM, and WHERE are all query tables. We can simply understand them as DQL statements.

SELECT select_list [ INTOnew_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUPBY group_by_expression ] 

DDL

The D in the middle refers to Definition, which we simply understand as the language used to create libraries and tables.

CREATE创建 
ALTER修改 
DROP删除COMMENT 注释 

DML

M stands for manipulation. We simply understand it as adding, updating and deleting operations for each piece of data in the data table.

INSERT添加 
UPDATE 更新 
DELETE删除 

DCL

C stands for control, which simply means transactions in mysql.

COMMIT提交 
ROLLBACK 回滚 
SET TRANSACTION设置当前事务的特性,它对后面的事务没有影响 

mysql login

for example:

Enter the following command on the command line interface to log in to MySQL:

mysql -u username -p 

Among them, "username" is your MySQL username, and "-p" means you need to enter a password.

Next, you will be prompted for your password. After entering the password and pressing Enter, if the login is successful, you will see the MySQL prompt, indicating that you have successfully logged in to the MySQL server.

If you are not logging in to this machine, the -h parameter is required.

"-h" is an option in the MySQL command line login, used to specify the host name or IP address of the MySQL database server.

DDL

Create database

Create database directly

Syntax: Note that the statements in square brackets are optional

CREATE DATABASE [IF NOT EXISTS] 数据库名 

Although it is optional, I recommend adding it, otherwise an error will be reported if the data does not exist.

Compared with js, it is actually object-oriented new and a new database.

Create a database by specifying the character set

In 5.7, the default character set of MySQL only supports English, so the character set is generally set to utf8 to support all languages. Mysql 8 defaults to utf8mb4. We must use 8. People have officially given up maintaining 5.7.

Here is a brief talk about the difference between utf8 and utf8mb4:

UTF-8 and UTF8MB4 are two character sets in MySQL.

  • UTF-8: This is a common Unicode character set that can represent most characters, but cannot represent some special characters (such as Emoji characters).
  • UTF8MB4: This is an extended UTF-8 character set that can represent all Unicode characters, including Emoji characters.

When you need to store more characters, especially Emoji characters, it is recommended to use the UTF8MB4 character set. When using the UTF8MB4 character set, you need to use 4 bytes to store a character, but with the UTF-8 character set, you only need to use 3 bytes. Therefore, if your data storage needs need to store more characters, using the UTF8MB4 character set may incur more space overhead.

grammar:

CREATE DATABASE [IF NOT EXISTS] 数据库名 CHARACTER 字符集 

Compared with js, it is actually object-oriented new, a new database, and then what is the parameter character set?

Sorting rules

Let’s illustrate the data sorting rules of utf8_general_ci and utf8_bin specified by the utf8 character set:

  • utf8_general_ci refers to the unclear sense of upper and lower case, a and A will be judged consistent in the character set.
  • utf8_bin needs to be distinguished

grammar:

CREATE DATABASE [IF NOT EXISTS] 数据库名 CHARACTER 字符集 COLLATE utf8_bin 

Compared with js, this is to pass the character set and sorting rules as parameters.

View database

View all databases

SHOW databases 

View the specified database

You can see information such as table creation statements and encoding methods.

SHOW CREATE DATABASE 数据库名 

Modify database

This is rarely used, and I feel like changing this is a big deal.

You can only modify the character set and collation of the database, but not the name of the database.

grammar:

ALTER DATABASE 数据库名 CHARACTER SET 字符集 [COLLATE 排序规则] 

Compared with js, you change the value of the object, which is a setter method to change the internal value.

Delete database

grammar:

DROP DATABASE 数据库名 

Compared with js, it is to let the system garbage collect the instance objects you create.

Use database

View the database in use

grammar

SELECT DARAVASE() 

Switch database

USE 数据库名 

Operation sheet

Create table

CREATE TABLE 表名 (字段名1 数据类型,字段名2 数据类型,....) 

Compared with js, it is similar to object-oriented creation of an instance of a table. The parameters passed into the instance are the field name and data type.

For example:

CREATE TABLE student {id INT,name VARCHAR(20),birthday date
} 

Here we sort out all data types:

integer

Let’s start with the most basic data type, integer. First, use a table to summarize:

type of data Number of bytes signed minimum signed maximum unsigned minimum unsigned maximum value
TINYINT 1 -128 127 0 255
SMALLINT 2 -32768 32767 0 65535
MEDIUMINT 3 -8388608 8388607 0 16777215
INT 4 -2147483648 2147483647 0 4294967295
BIGINT 8 -9223372036854775808 9223372036854775807 0 18446744073709551616

By default, integers are positive and negative. If you need a pure positive number, add the unsigned keyword.

floating point

type of data Number of bytes Remark
float 4 Single precision floating point
double 8 Double precision floating point

Note here that the floating point type can indicate how many accurate

CREATE TABLE test_float (num float(5, 2)
) engine=innodb charset=utf8; 

From this result, we summarize the usage rules of float(M,D) and double(M,D):

  • D represents the precision after the decimal point of floating point data. If it exceeds D digits, it will be rounded, that is, 1.233 will be rounded to 1.23, and 1.237 will be rounded to 1.24.
  • M represents the total number of digits in floating-point data. D=2 means a total of five digits are supported, that is, only three digits are supported before the decimal point.

Fixed point type

The fixed-point type is decimal, and its usage is the same as the floating-point number above.

  • The rules of decimal(M,D) are the same as float/double, but the difference is that float/double defaults to the actual precision when M and D are not specified, while decimal defaults to decimal(10, 0) when M and D are not specified.

date type

Next, let’s take a look at the date types in MySQL. MySQL supports five forms of date types: date, time, year, datetime, and timestamp. Use a table to summarize these five date types:

type of data Number of bytes Format Remark
date 3 yyyy-MM-dd Store date value
time 3 HH:mm:ss Store hours, minutes and seconds
year 1 yyyy Storage years
datetime 8 yyyy-MM-dd HH:mm:ss Store date+time
timestamp 4 yyyy-MM-dd HH:mm:ss Store date + time, can be used as timestamp

Character types: char and varchar types

Char is tricky, it stores bytes, but one Chinese character does not correspond to one byte. Varchar is based on characters, so we usually use varchar

1.char is a fixed-length string, and its length range is 0-255 and has nothing to do with the encoding method. No matter what the actual length of the character is, it will be stored according to the specified length. If it is not enough, it will be filled with spaces; varchar is a variable-length string. The length range in the utf8-encoded database is 0-21844
2. The actual number of bytes occupied by char is the number of bytes occupied by the stored characters, and the actual number of bytes occupied by varchar is the stored characters +1 or +2 or + 3
3.MySQL will process all trailing spaces when processing char type data, but not varchar type data.

View table

View all tables

show tables 

View table structure

DESC 表名 

View the table creation statement

SHOW CREATE TABLE 表名; 

The default engine for table creation is innodb, the default data is filled with nulls, and the default sorting is case-insensitive.

Copy table structure

grammar:

CREATE TABLE 新表名 LIKE 旧表名 

Delete table

DROP TABLE 表名 

DML

Insert record

INSERT INTO 表名 (字段名1,字段名2...) VALUES (值1,值2...) 

Note that, except for numeric types, values ​​of other field types must be enclosed in quotes.

worm replication

Based on the existing data, copy the original data and insert it into the corresponding table.

Note that you need to create a table with the same structure as the source table for copying.

INSERT INTO 表名1 SELECT * FROM 表名2 

Update table record

Unconditional updates

UPDATE 表名 SET 字段1=值1[字段2=值2...] 

The value of the entire column will change

Update with conditions

UPDATE 表名 SET 字段1=值1[字段2=值2...][WHERE 条件] 

Delete Record

Delete conditionally

Delete certain rows of data:

DELETE FROM 表名 WHERE 条件 

Delete without conditions

grammar

DELETE FROM 表名 

All data in the table will be deleted

DQL data query language

Single table query

Simple query

Query all data in the table

grammar

SELECT * FROM 表名 

Compared with js, this is the for loop statement

const result = [];
for(let i = 0; i < 学生表数组.length; i++) {result.push(学生表数组[i])
}
return result; 

Query all data for a specific column in the table

Of course, you can query specific fields:

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

Compared with js, this is the for loop statement

// 下面的pick函数,就是从一个对象里取对应属性名的函数
// 很多工具库都有,比如loadash,自己写一个也很简单
const result = [];
for(let i = 0; i < 学生表数组.length; i++) {result.push(pick(学生表数组[i], ...所有字段))
}
return result; 

Alias ​​query

Aliasing is to give a custom name to the column name. We usually use the AS keyword to achieve this.

statement

SELECT 字段名1 AS 别名,字段2 AS 别名... FROM 表名 AS 表的别名 

Remove duplicate values

When querying the specified column, if there is duplicate data in the specified column, it will be displayed by default.

SELECT DISTINCT 字段名 FROM 表名 

For example, the data you query:

SELECT DISTINCT name FROM student 

will filter out all rows with the same name field

Query results participate in calculations

In the query statement, the queried column can perform mathematical operations (addition, subtraction, multiplication, and division) with other values. The operation results will only affect the display and will not affect the data in the table.

grammar

SELECT 列名1 + 固定值 FROM 表名
SELECT 列表1 + 列名2 FROM 表名 

The above is limited to the addition of numbers. For example, we have a table that is

Then we add 5 years old in the age column, then it will be displayed

Of course, you can also use aliases to make the column names look better.

As follows, by the way, columns and column addition are also among them

comparison operator

In query conditions, you can use a variety of comparison operators to express query conditions.

For example:

  • = equal to -> greater than
  • < less than
  • <= less than or equal to ->= greater than or equal to
  • <> or
  • != is not equal to

Logical Operators

  • and or && multiple conditions are met at the same time
  • or or || one of multiple conditions is met
  • not or! dissatisfied

Query within the specified range in

grammar

SELECT 字段名 FROM 表名 WHERE 字段 [not] in (数据1,数据2...) 

fuzzy query

grammar

SELECT * FROM 表名 WHERE 字段名 like “通配符字符串” 
  • % means 0 or more characters (any number of characters)
  • _ represents a character

Query is null

To query data for which a field is empty (null), instead of using = null (null is not equal to any value), use is null instead.

For example:

SELECT * FROM student WHERE english IS null 

sort

The sort statement is executed after the SELECT statement

grammar

SELECT 字段名 FROM 别名 [WHERE 条件] ORDER BY 字段名 [ASC|DESC] 
  • ASC default ascending order
  • DESC descending order

single line function

A single-row function refers to calculating each row of data and obtaining one row of output results.

Numerical function

abs(x)

Find the absolute value

For example

SELECT ABS(-1) -- 返回1 

ceil(x)

Rounded up

For example

SELECT CEIL(1.5) --返回2 

floor(x)

Round down

round(x)

Rounding

String functions

concat(s1, s2,…sn)

Strings s1, s2 and other strings are combined into one string

locate(s1, s)

Get the starting position of s1 from the s string

lower(s)

Change all letters of s string to lowercase letters

upper(s)

Convert string to uppercase

replace(s, s1, s2)

Replace string s2 with string s and find the string s1

substr(s, start, length)

Intercept a substring of length length from the start position of string s

trim(s)

Remove leading and trailing spaces

aggregate function

Aggregation function query is a vertical query. It calculates the value of a column and returns a result value. The aggregate function ignores null values.

count

Count the number of records in the specified column. Records that are NULL will not be counted.

SUM

Calculate the numerical sum of the specified column. If it is not a numeric type, the calculation result is 0

MAX

Calculate the maximum value of the specified column

MIN

Calculate the minimum value of the specified column

AVG

Calculate the average of the specified column. If it is not a numeric type, the calculation result is 0

Group query

Group query refers to using the GROUP BY statement to group query information, with the same data as a group.

The execution order of the GROUP BY statement is after the WHERE statement and before the SELECT statement.

grammar

SELECT 字段1,字段2...FROM 表名 GROUP BY 分组字符安 [HAVING 条件] 

GROUP BY groups the same content in the group field results as a group

Example

SELECT * FROM student3 GROUP BY age 

Group the same age into a group

The above usage is wrong. The purpose of grouping is for statistics and is generally used together with aggregate functions.

For example:

SELECT SUM(math), sex FROM student GROUP BY sex; 

Comparison between WHERE and HAVING

  • having is to filter the data after grouping, and where is before grouping
  • Aggregate functions can be used in the having statement, but aggregate functions cannot be used after where.

limit

LIMIT is to limit the number of query records and should be placed at the end of the SQL statement.

grammar:

LIMIT offset, length;或者 limit length 

offset is the offset, which can be thought of as the number of skipped records

Summarize the writing order and execution order of query statements

Writing order

SELECT field FROM table name WHERE condition GROUP BY field HAVING condition ORDER BY field LIMIT offset, length

Execution order

  • from table name
  • where condition
  • group by field
  • having condition
  • select field
  • order by field
  • limit

constraints and strategies

primary key constraints

The role of primary key

Used to uniquely identify a record, such as a person's ID number. Every table should have a primary key, and every table can only have one primary key.

Usually, the business field is not used as the primary key. An id field is designed for each table separately, and the id is used as the primary key. The primary key is used by the database and the program, not the final customer, so it does not matter if the primary key has no meaning. The main thing is not to repeat it. , it just needs to be non-empty.

Add primary key when creating table

create table stu1 (id int primary key,name varchar(20)
) 
create table stu1 {id int,name varchar(20),primary key(id)
} 

Primary key auto-increment strategy

create table stu1 (id int primary key auto_increment,name varchar(20)
) 

non-null constraint

NOT NULL, indicating that this column is required when adding data

mysql> CREATE TABLE tb_dept4-> (-> id INT(11) PRIMARY KEY,-> name VARCHAR(22) NOT NULL,-> location VARCHAR(50)-> ); 

unique constraint

The column to which a unique constraint is added cannot be repeated, but can be null

CREATE TABLE Employees
( employee_name CHAR(50) NOT NULL, social_num INTEGER, phone INTEGER, UNIQUE (social_num)
) 

default constraints

The syntax is default

mysql> CREATE TABLE tb_dept3-> (-> id INT(11) PRIMARY KEY,-> name VARCHAR(22),-> location VARCHAR(50) DEFAULT 'Beijing'-> ); 

table relationship

In real life, there is a relationship between entities, such as: husband and wife, department and employee, teacher and student, etc. The table we design is a description of the entity in reality, so when we design the table, we This relationship should be reflected.

The relationships between tables mainly include: one-to-many (many-to-one), one-to-one, and many-to-many.

One-to-many (many-to-one)

For example: classes and students, departments and employees, customers and orders, categories and products, etc.

Table creation principles:

It does not have to be a foreign key. This relationship can be formed by one column of table A corresponding to the primary key of table B.

many to many

For example: teachers and students, students and courses, users and roles

Many-to-many relationship, table creation principle: you need to create a third table, with at least two fields in the intermediate table

Multi-table query

Cartesian product

The Cartesian product in MySQL refers to when performing a JOIN operation between multiple tables without specifying conditions, the returned results are all possible combinations in these tables.

For example, suppose we have two tables A and B, where A contains two rows (1 and 2) and B contains three rows (A, B and C),

 SELECT * FROM A, B; 

Then the returned result set will contain 6 rows, namely:

1 A
1 B
1 C
2 A
2 B
2 C 

Converted to javascript is a for loop between two tables

const result = [];
for(let i = 0; i < A表.length; i++){ for(let j = 0; j < B表.length; j++){result.push(A[i], B[j])} 
} 

Multi-table query

To clear the Cartesian product, you need to use a join query. Join queries are divided into inner joins and outer joins.

Introduction to JOIN statement

1.INNER JOIN INNER JOIN is the most commonly used JOIN type. It only returns rows common to the two tables. It looks for values ​​that exist in both tables and combines the values ​​into a result set.

For example, suppose you have two tables, one is "orders" and the other is "customers". There is a "customer_id" column in both tables, and the data from these two tables can be merged using INNER JOIN:

SELECT *
FROM orders
INNER JOIN customers
ON orders.customer_id = customers.customer_id; 

This is actually a screening based on the Cartesian product above.

Converted to javascript is a for loop between two tables

const result = [];
for(let i = 0; i < orders.length; i++){  for(let j = 0; j < customers.length; j++){if(orders[i].customer_id === customers[j].customer_id){result.push(orders[i], customers[j])}} 
} 

2.LEFT JOIN LEFT JOIN returns all rows in the left table, even if there are no matching rows in the right table. If there are no matching rows, the columns of the table on the right will appear as NULL.

For example, suppose you have two tables, one is "orders" and the other is "customers". Use LEFT JOIN to list all orders and the information of the customer to which the order belongs:

SELECT *
FROM orders
LEFT JOIN customers
ON orders.customer_id = customers.customer_id; 

Converted to javascript is a for loop between two tables

const result = [];
for(let i = 0; i < orders.length; i++){ for(let j = 0; j < customers.length; j++){if(orders[i].customer_id === customers[i].customer_id) {result.push(A[i], B[j])}} 
} 

3.RIGHT JOIN RIGHT JOIN is similar to LEFT JOIN, but it returns all rows in the right table, even if there are no matching rows in the left table. If there are no matching rows, the columns of the left table will appear as NULL.

For example, suppose you have two tables, one is "orders" and the other is "customers". Use RIGHT JOIN to list all customers' information together with their orders:

SELECT *
FROM orders
RIGHT JOIN customers
ON orders.customer_id = customers.customer_id; 

4.FULL OUTER JOIN MySQL does not support FULL OUTER JOIN, but you can use the UNION operator to combine LEFT JOIN and RIGHT JOIN to obtain the same result.

For example, suppose you have two tables, one is "orders" and the other is "customers". Use UNION, LEFT JOIN, and RIGHT JOIN to implement FULL OUTER JOIN:

SELECT *
FROM orders
LEFT JOIN customers
ON orders.customer_id = customers.customer_id
UNION
SELECT *
FROM orders
RIGHT JOIN customers
ON orders.customer_id = customers.customer_id; 

UNION

UNIONIt is an operator used to merge two or more SELECT statements in the MySQL database. It can merge the result sets of two or more SELECT statements into one result set. UNIONDuplicate rows will be automatically removed and can be used if duplicate rows need to be included UNION ALL.

For example

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2; 
  • SELECT column_name(s) FROM table1and SELECT column_name(s) FROM table2respectively represent the two SELECT statements to be merged.
  • UNIONThe operator is used to merge result sets. It returns the union of two result sets, automatically removing duplicate rows.
  • If you want to keep duplicate rows, you can use UNION ALLthe operator.

subquery

For detailed exercises, please read this article: juejin.cn/post/708368…

The result of one SELECT statement as part of another SELECT syntax

grammar

SELECT 字段 ...FROM 表 WHERE 字段 运算符 (SELECT 字段... FROM 表) 

The result of a single-row subquery is a value.

Single-line operators =, >, >=, <, <=, !=

Multi-line operators in, any, all

Multiple column subquery

The result of the subquery is a single column, which is used as the result of the conditional subquery after WHERE. The result of the subquery is multiple columns, which must be used as a table after FROM.

grammar

SELECT 查询字段 FROM (子查询) 表别名 WHERE 条件 

Data backup and restore

When we perform data transmission, data storage and data exchange on the server, data failures may occur, such as unexpected shutdowns or storage media damage. Without CIA measures to back up and restore data, data may be lost.

mysqldump -u 用户名 -p 密码 数据库 > 文件的路径/文件名.sql 

Note that this backup is a table-level backup, and you need to create the database first when restoring.

affairs

What is a database transaction

A database transaction is a database operation (add, delete, modify) that accesses and possibly manipulates data items. These operations are either all executed or not executed at all. They are an indivisible unit of work.

purpose of transaction

  • Provides a way for database operations to recover from failure to a normal state
  • When multiple applications access the database concurrently, an isolation method can be provided between these applications to prevent each other's operations from interfering with each other.

operational transactions

There are two ways to perform transaction operations in mysql:

  • Automatically commit transactions* Each addition, deletion and modification statement of mysql is a separate transaction. By default, mysql will automatically start a transaction when executing each statement, and automatically submit the transaction after execution.
  • Manually commit the transaction* Transaction-related SQL statements* start transaction; Open the transaction* commit; Submit the transaction* rollback; Roll back the transaction

Example:

start transaction;
update xxx -- 因为这里没有提交事务,所以数据库的数据不会发生变化 

principles of affairs

After the transaction is started, all operations will be temporarily saved to the transaction log. The transaction log will only be synchronized to the data table after receiving the commit command. In other cases, the transaction log will be cleared (rollback, disconnect)

Transaction concurrency exception

Problems that may arise during concurrent transaction operations

  • Rollback lost (problem with concurrent transactions)

"Rollback lost" means that when performing a rollback operation in a MySQL transaction, if some modifications have been committed before the rollback, these modifications will be lost, which means that the rollback operation cannot undo these submitted modifications.

For example, suppose in a MySQL transaction, some insert or update operations are performed first, but a rollback operation is performed before the transaction is committed. If other connections or transactions have already committed some modifications before rolling back, these modifications will not be rolled back, and the final data in the database will contain these committed modifications.

  • coverage lost

"Overwrite loss" means that when performing an update operation in MySQL, if two or more concurrent connections or transactions modify the same row of data at the same time, one of the modifications will overwrite the results of other modifications, causing the results of other modifications to be lost.

For example, suppose there are two concurrent connections or transactions trying to update the same row of data at the same time. If both connections or transactions perform update operations, the results of the last update operation will overwrite the results of the previous update operation. In this way, the results of the previous update operation are overwritten, that is, "overwrite loss" occurs.

  • dirty read

One transaction reads uncommitted data from another transaction

  • non-repeatable read

"Non-repeatable read" refers to the situation in MySQL where the same row of data is read multiple times in the same transaction, but other transactions modify the row of data during this period, resulting in different results from the two previous reads.

For example, assume that the following operations are performed in a transaction:

1. Read a certain row of data;
2. Another transaction modifies the row of data;
3. Read the same row of data again.

If another transaction modifies the row of data before the second read, the data obtained in the second read will be different from the data read in the first time, resulting in a non-repeatable read.

  • phantom reading

"Phantom read" refers to a situation in MySQL where the same query statement is executed multiple times in the same transaction, but during this period other transactions insert or delete rows that meet the query conditions, resulting in different query results between the two previous times.

For example, assume that the following operations are performed in a transaction:

1. Execute a certain query statement and return a set of qualified rows;
2. Another transaction inserts some new qualified rows;
3. Execute the same query statement again.

If another transaction inserts new qualifying rows before executing the query statement for the second time, the second query will return more rows than the first query, resulting in phantom reads.

isolation level

I think that the default isolation level of the InnoDb storage engine in Mysql is Repeatable Read, so we take a look at what concurrency exceptions this isolation level can solve.

  • Rollback lost* ok
  • Dirty read* ok
  • Non-repeatable read* ok
  • Coverage lost* ok
  • Phantom reading* Logically speaking, this is not OK, but mysql can handle it too.

View and modify isolation levels

Check

SELECT @@transacation_isolation 

Revise

SELECT @@session.tx_isolation='隔离级别' 

Create user

grammar

CREATE USER '用户名'@'主机名' IDENTIFIED BY '密码' 

change Password

ALTER USER USER() IDENTIFIED BY `new_password` 
  • Username: The username that will be created
  • Host name: Specify the host on which the user can log in. If it is a local user, localhost can be used. If you want the user to log in from any remote host, you can use the wildcard character %.
  • Password: The user's login password. The password can be empty. If it is empty, the user can log in to the server without a password.

index

Simply put, an index is a directory that can quickly help us find the corresponding data.

Generally speaking, the index itself is also very large and cannot be stored entirely in memory, so the index is often stored on disk in the form of an index file.

Although the index greatly improves the query speed, it also reduces the speed of table updates, such as INSERT, UPDATE and DELETE on the table. Because when updating the table, Mysql not only needs to save the data, but also save the index file. Every time a field that adds an index column is updated, the index information after the key value changes caused by the update will be adjusted.

Ordinary index

There are no restrictions on its use, it is allowed to be created on all data types, and it can have duplicate values ​​and null values. An index contains only a single column, and a table can have multiple single-column indexes.

Created when creating table

grammar

INDEX 索引名 (列名) 

Example

create table student (id int primary key,name varchar(20),age int,index student_name_index(name)
) 

Create directly

CREATE INDEX 索引名 ON 表名(列名) 

Test whether the creation is successful

show index from student2 

unique index

Similar to a normal index, the difference is that the value of the index column must be unique, but null values ​​are allowed. In the case of a composite index, the combination of column values ​​must be unique.

grammar

UNIQUE INDEX 索引名 (列名) 

at last

We have prepared a front-end information package for everyone. Contains 54, 2.57G front-end related e-books, "Front-end Interview Guide (with answers and analysis)", video tutorials on difficult and key knowledge (full set).



Friends in need can click on the card below to receive it and share it for free

Guess you like

Origin blog.csdn.net/web2022050901/article/details/129379571