当前位置:网站首页>SQL table columns and statements of database

SQL table columns and statements of database

2022-06-13 05:11:00 I love Qianxi

One 、 data type

1、 Interview questions
char and varchar The difference between

1 Similarities : Both are 32 Bit length string type
2 The difference
char The type is fixed length , One time offer 32 Storage space of character length , Be dissatisfied , Supplement with spaces ; At most 255 Characters .
varchar It's variable length , Calculate and judge the string length , Allocate storage space on demand , It will take another byte to record the character length , exceed 255, Will use 2 Byte record length , At most 65535 Characters .

char and varchar How to choose ?

(1) char type , A fixed length string of characters , Such as mobile phone number , ID number , Bank card number , Gender, etc
(2) varchar type , Strings of indefinite length can use

2、enum Enumeration type

enum(‘bj’,‘sh’,‘sz’,‘cq’)
The indexes are 0 1 2 3, Digital classes are prohibited enum

3、 Numeric type

1、tinyint
Minimal integer data type -128 - 127
2、int
The mobile phone number cannot be saved to int Of , In general use char Type stores the phone number

4、 Time

1、timestamp
1970-01-01 to 2038-01-19
2、datetime
1000-01-01 to 9999-12-31

Two 、 Table properties

1、 Storage engine :engine=InnoDB

2、 Character set :charset=utf8mb4

utf8 and utf8mb4 The difference between
A Chinese in utf8 Middle occupancy 3 Byte length , stay utf8mb4 Middle occupancy 4 Bytes , however utf8 Not many characters are supported , There may be garbled code , Best use utf8mb4.

3、 Sort rule ( Proofread rules collation)

It mainly aims at the case of English strings

3、 ... and 、 Column properties and constraints

Primary key :primary key(PK)

Value must be unique , Do not repeat , Do not empty , Number column , Integer column , Unrelated column , Self increasing . It's a constraint , It is also an index type , There can only be one primary key in a table .

Non empty :not null

The value of the column cannot be empty , For normal columns , Try to set to not null

The default value is :default

The default values for numeric columns use 0, The string type is set to null

only : unique

Like cell phone number , The ID number can not be repeated.

Self increasing : auto_increment

For digital column self growth , Automatic generation of sequence values

Unsigned :unsigned

For digital Columns , Non negative numbers are unsigned

notes :comment

describe

Four 、SQL Statement application

1、DDL( Data definition language )

Library operation
1、 Building database

mysql> create database free charset utf8mb4;
Query OK, 1 row affected (0.01 sec)

2、 Query database creation information ( Belong to DQL)

mysql> show create database free;
+----------+------------------------------------------------------------------+
| Database | Create Database                                                  |
+----------+------------------------------------------------------------------+
| free     | CREATE DATABASE `free` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ |
+----------+------------------------------------------------------------------+

3、 Change the warehouse

mysql> alter database liyu charset utf8mb4;
 Library liyu The character set of consists of latin1 become utf8mb4

4、 Delete library

mysql> drop database liyu;
Query OK, 0 rows affected (0.02 sec)

Table operations
Specification for building tables and databases :

1、 Table name , The library name must be lowercase ( because windows Case insensitive in , The same file name cannot be distinguished between two sets of case )
2、 Cannot start with a number
3、 I won't support it -, Support _
4、 Inner function names cannot be used
5、 The name is related to the business function

1、 Build table

create table liyu (
ID int not null primary key AUTO_INCREMENT comment ' Student number ';
name varchar(255) not null comment ' full name ';
age tinyint unsigned not null default 0 comment ' Age ';
gender eunm('m','f','n') not null default 'n' comment ' Gender '
)charset=utf8mb4 engine=innodb;

2、 Change table
a. Modify table structure ( add to , Delete column )
Add columns to the above table ( cell-phone number 15891007817)

alter table liyu add telnum char(11) not null unique comment ' cell-phone number ';

stay name Add after qq Column

alter table liyu add qq varchar(255) not null unique  comment 'qq Number ' after name;

Add... To the first column sid

alter table liyu add sid varchar(255) nit null unique comment ' Student number ' first;

Delete the column added above

alter table liyu drop qq;

View column information

desc liyu;
mysql> desc student;
+--------+---------------------+------+-----+---------+----------------+
| Field  | Type                | Null | Key | Default | Extra          |
+--------+---------------------+------+-----+---------+----------------+
| id     | int(11)             | NO   | PRI | NULL    | auto_increment |
| name   | varchar(255)        | YES  |     | NULL    |                |
| age    | tinyint(3) unsigned | NO   |     | 0       |                |
| gender | enum('m','f','n')   | NO   |     | n       |                |
+--------+---------------------+------+-----+---------+----------------+

show create table liyu;  View the table creation statement 

b. Change the data type of the column
take age The property of the is changed to int

alter table liyu modify  age int;

2、DCL( Data control language )

The most important thing is grant Authorization and revoke Cancel Authorization

3、DML( Data operation language )

1、insert

mysql> insert into student (name,age,gender) values ('liyu',23,'f');
mysql> select * from student;
+----+------+-----+--------+
| id | name | age | gender |
+----+------+-----+--------+
|  1 | liyu |  23 | f      |
+----+------+-----+--------+

2、update( combination where)

mysql> select * from student;
+----+------+-----+--------+-------+
| id | name | age | gender | qq    |
+----+------+-----+--------+-------+
|  1 | liyu |  23 | f      |       |
|  2 | free |  22 | m      | 56787 |
+----+------+-----+--------+-------+

mysql> update student set qq='123456' where id=1;

mysql> select * from student;
+----+------+-----+--------+--------+
| id | name | age | gender | qq     |
+----+------+-----+--------+--------+
|  1 | liyu |  23 | f      | 123456 |
|  2 | free |  22 | m      | 56787  |
+----+------+-----+--------+--------+

3、delete
Logical deletion , It is very slow to delete tens of millions of rows of big data

mysql> select * from student;
+----+------+-----+--------+--------+
| id | name | age | gender | qq     |
+----+------+-----+--------+--------+
|  1 | liyu |  23 | f      | 123456 |
|  2 | free |  22 | m      | 56787  |
+----+------+-----+--------+--------+

mysql> delete from student where id=2;

mysql> select * from student;
+----+------+-----+--------+--------+
| id | name | age | gender | qq     |
+----+------+-----+--------+--------+
|  1 | liyu |  23 | f      | 123456 |
+----+------+-----+--------+--------+

Physical delete ,truncate,DDL operation

mysql> truncate table student;

Interview questions :

delete and truncate The difference between
1、delete Logical line by line deletion , It will not reduce the starting value of self growth , Efficiency is very low , There are many fragments , Will affect performance .
2、truncate Physical delete , Empty the area in the table segment , There will be no debris , Higher performance . Only the whole table can be emptied !!! If you want to delete a few lines, you still have to use delete.

Pseudo delete :
Use update Instead of delete, Pseudo delete
1、 Add status column state(1 On behalf of there ,0 On behalf of the delete )

mysql> alter table student add state tinyint not null default 1;

mysql> select * from student;
+----+------+-----+--------+--------+-------+
| id | name | age | gender | qq     | state |
+----+------+-----+--------+--------+-------+
|  1 | liyu |  23 | f      | 123456 |     1 |
|  3 | free |  22 | m      | 789    |     1 |
+----+------+-----+--------+--------+-------+

2、 Use update simulation delete

mysql> update student set state=0 where id=3;

mysql> select * from student;
+----+------+-----+--------+--------+-------+
| id | name | age | gender | qq     | state |
+----+------+-----+--------+--------+-------+
|  1 | liyu |  23 | f      | 123456 |     1 |
|  3 | free |  22 | m      | 789    |     0 |
+----+------+-----+--------+--------+-------+

3、 Business statement modification , Just check state by 1 Of

mysql> select * from student where state=1;
+----+------+-----+--------+--------+-------+
| id | name | age | gender | qq     | state |
+----+------+-----+--------+--------+-------+
|  1 | liyu |  23 | f      | 123456 |     1 |
+----+------+-----+--------+--------+-------+

4、DQL( Data query language )

1、select

effect : obtain MySQL Data rows in

a、 Use alone select,select @@xxx, Get parameter information

mysql> select @@port;
+--------+
| @@port |
+--------+
|   3306 |

b、select function ( )

ysql> select now();    Query time 
+---------------------+
| now()               |
+---------------------+
| 2021-05-24 17:22:32 |
+---------------------+

mysql> select database();   # Query which library 
+------------+
| database() |
+------------+
| free       |
+------------+

c、SQL92 Standard usage Syntax
select Syntax execution order ( Single table )
select Start ------> from Clause ------>where Clause ------>group by Clause -------->select Post execution condition -------->having Clause ------->order by ------->limit

from

select * from  Table name  # It is suitable for tables with fewer data rows , Less used in production 
select name,age from  Table name 

where
where Cooperate with equivalent query ( Inquire about city The cities in the table are Chinese )

select * from world.city where countrycode='CHN';

where Cooperate with unequal query ( The world population is less than 1000 Human city )

select * from world.city where population<1000;

where Cooperate with fuzzy query ( Query country code is c The first city )

select * from worl.city where countrycode like 'c%';
like Statements in Mysql in , Do not appear % In the previous case , Because the efficiency is very low , Don't walk index 

where With logical connector (and,or Query the urban population in 1w To 2w Between )

select * from world.city where population>10000 and population<20000;( barring 1w and 2w)
select * from world.city where population between 10000 and 20000;( Include 1w and 2w)

Check the city information of the United States or China (union all)

select * from city where countrycode='CHN'
union (all)
select * from city where countrycode='USA'

union It's going to be weightless ,union all It's not going to be heavy

group by
group by Apply with aggregate function
Aggregate functions :

avg(),sum(),count(),max(),min(),group_concat()
group_concat() Column to row means

Count the total population of each country

select countrycode,sum(population) from city group by countrycode;

Count the number of cities in each country

select countrycode,count(id)from city group by countrycode;

Count the names of provinces in each country

select countrycode,group_concat(district) from city group by countrycode;

List the city names of each province in China

select district,group_concat(name) from city where countrycode='CHN' group by district;

Count the total population of each province in China

select district,sum(population) from city where countrycode='CHN' group by district;

having
having amount to where, But it can only be used in group by Back
According to statistics, the total population of each province in China is greater than 1000w Province and total population of

select district,sum(population) from world.city where countrycode='CHN' group by district having sum(population)>1000000 ;

having The latter condition is not indexed , Some optimization methods can be used to deal with
order by
Count the population of each province in China , And sort the population

select district,sum(population) from world.city where countrycode='CHN' group by district order by sum(population);
 To reverse the order, add desc

limit
Count the population of each province in China , And output in descending order , Before display 5 name

select * from world.city where countrycode='CHN' order by population desc limit 5;
 Show 6-10 That's ok 
limit 5,5; # Skip the former 5 That's ok , Re display 5 That's ok 

5、 ... and 、 Multiple table joins

The structure of the four tables is as follows :
 Insert picture description here

1、 Internal connection A join B on A.x=B.y
lookup a The teacher and the course he taught

select teacher.tname,course.cname from teacher join course on teacher.tno = course.tno where teacher.tname='a';

2、 Count the total score of each course

select course.cnme,sum(sc.score) from course join sc on course.cno = sc.cno group by course.cno;

group by stay sql_mode Affected by , If group by If the primary key is followed, no error will occur .
 Insert picture description here
3、 Inquire about oldguo A list of the names of the students taught by the teacher

select teacher.tname,group_concat(student.sname) 
from teacher
join course 
on teacher.tno=course.tno 
join sc 
on course.cno=sc.cno 
join student 
on sc.sno=student.sno 
where teacher.tname='oldguo';

4、 Query the list of student names taught by all teachers

select teacher.tname,group_concat(student.sname) 
from teacher
join course 
on teacher.tno=course.tno 
join sc 
on course.cno=sc.cno 
join student 
on sc.sno=student.sno 
group by teacher.tno;

Alias
Table alias (as)

select te.tname,st.sname from teacher as te join student as st on .......

6、 ... and 、 Indexes

1、 Classification of indexes

1、 Index function

An index is like a table of contents in a book , The purpose is to optimize queries

2、 Types of indexes ( Algorithm )

B Tree index ( a key B-tree,B+tree,B*tree)
Hash Indexes
R Trees
Full text
GIS

3、B+tree
 Insert picture description here
B+tree Than B-tree There are two-way pointers to adjacent leaf nodes , Convenient continuous access , Range queries , The viewing range is adjacent ( such as >5)
4、B*tree

mysql The most used is B*tree
Compared with B+tree More two-way pointers between branch nodes .
 Insert picture description here

2、 How the index is generated

1、 Functional classification
a、 Secondary index (S) How to build B Tree structure ?

1、 Secondary indexes are generated based on the columns of the table
2、 Get all the values of the index column ( Take out all key values )
3、 Sort all key values
4、 Drop all key values in order Btree Indexed Leaf node On
5、 Then the branch node and root node are generated
6、 Leaf nodes store key values , It also stores pointers to adjacent leaf nodes , In addition, the pointer of the original table data will be saved (page).

b、 Clustered index ( C) How to build B Tree structure ?

1、 There are primary key columns when creating tables (ID)
2、 Table for data storage , According to ID Column order , Store row by row data on the data page in an orderly manner ( This action is called the clustered index organization table )
3、 The data pages in the table are used as leaf nodes of the clustered index , It is equivalent to putting the value of the entire row of the table in the leaf node
4、 The primary key values of leaf nodes are generated into upper branch nodes and root nodes

The secondary index just takes out the values of a single column as leaf nodes , The clustered index takes the value of the entire row as the leaf node . The secondary index is used to assist the clustered index .
2、 Secondary index segmentation
a、 Single column secondary index
b、 Joint multi column secondary index ( Overlay index )
c、 unique index
3、 About how the height of the index tree is affected ?

1、 Multiple data lines , We need to divide the databases and tables
2、 If the character length of the index column is very long, it will affect the height , Prefix index
3、char,varchar,char Type may affect height , The data type of the table should be designed reasonably
4、enum Optimize index height , If you can use it, you can use it

3、 Index management commands

We can do a stress test first , To the database oldboy Library creates a table , Write in table 100 Ten thousand rows of data , Proceed again 100 Users ,20000 Concurrent tests

create table t100w (
id int,num int,
k1 char(2),
k2 char(4),
dt timestamp);
delimiter //
create  procedure rand_data(in num int)
begin
declare str char(62) default 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
declare str2 char(2);
declare str4 char(4);
declare i int default 0;
while i<num do
set str2=concat(substring(str,1+floor(rand()*61),1),substring(str,1+floor(rand()*61),1));
set str4=concat(substring(str,1+floor(rand()*61),2),substring(str,1+floor(rand()*61),2));
set i=i+1;
insert into t100w values (i,floor(rand()*num),str2,str4,now());
end while;
end;
//
delimiter ;

 Insert 100w Data :
call rand_data(1000000);


 Exit database , Enter at the command line 100 Users ,2000 Concurrent times 
mysqlslap --defaults-file=/etc/my.cnf \
--concurrency=100 --iterations=1 --create-schema='oldboy' \
--query="select * from oldboy.t100w where k2=' XYVW '" engine=innodb \
--number-of-queries=2000 -uroot -p password  -verbose
 You can see that the index execution is not particularly slow , To spend 700 More than a second 
rk
        Running for engine rbose
        Average number of seconds to run all queries: 770.099 seconds

1、 Create a normal index

mysql> alter table t100w add index idx_k2(k2);
 to k2 Column creation index 

After creating the index , Let's do the above test

Average number of seconds to run all queries: 0.281 seconds

It only cost 0.28 second ! What's the concept , The index is awesome !
Let's take a look at the index created

mysql> desc t100w;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| id    | int(11)   | YES  |     | NULL              |                             |
| num   | int(11)   | YES  |     | NULL              |                             |
| k1    | char(2)   | YES  |     | NULL              |                             |
| k2    | char(4)   | YES  | MUL | NULL              |                             |
| dt    | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
k2 Column MUL Is the secondary index 

mysql> show index from t100w\G
*************************** 1. row ***************************
        Table: t100w
   Non_unique: 1
     Key_name: idx_k2
 Seq_in_index: 1
  Column_name: k2
    Collation: A
  Cardinality: 3611
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: BTREE
      Comment:
Index_comment:

2、 Create unique index

mysql> alter table t100w add unique index idx_k1(k1);
ERROR 1062 (23000): Duplicate entry 'Od' for key 'idx_k1'
 You can try with the above command , If not, it means that there are duplicate values 

3、 Create prefix index ( For Strings )

mysql> alter table city add index idx_name(name(5));

4、 Create a federated index
establish city Tabular population and countrycode

mysql> alter table city add index idx_co_po(countrycode,population);

5、 Delete index
First, you can check the index

mysql> show index from t100w;
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| t100w |          1 | idx_k2   |            1 | k2          | A         |        3611 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+----------+--------------+-------------+-

Delete index

mysql> alter table city drop index idx_k2

4、 Implementation plan

1、 effect

Before launching a new query statement , Predict the performance of statements in advance
In case of performance problems , Find a reasonable solution

2、 Execute the plan to get

mysql> desc select * from oldboy.t100w where k2='XYVW'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t100w    
   partitions: NULL
         type: ref       
possible_keys: idx_k2
          key: idx_k2
      key_len: 17
          ref: const
         rows: 292
     filtered: 100.00
        Extra: NULL
  
type:ref   The application level of the index   *****
possible_keys: idx_k2    Indexes that may be used 
key: idx_k2     Index actually used 
key_len: 17    Related to the union index , Union index coverage length 
rows: 292    Number of rows of queries ( The less, the better. )
Extra: NULL  *****

3、 Analysis of execution plan
type:ref The application level of the index

 From top to bottom , Performance gets better in turn 
ALL     Full table scan , Don't walk index , Whether there is an index or not 
       1、 Not indexed , So don't go 
       2、 Index , But I won't go ( Do not use index columns as search criteria ; use like, Before and after %, If you want to add , Just add... At the end %;=)
       
Index     Full index scan 
mysql> mysql> desc select k2 from t100w;
+----+-------------+-------+------------+-------+---------------+--------+---------+------+--------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key    | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+--------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | t100w | NULL       | index | NULL          | idx_k2 | 17      | NULL | 997344 |   100.00 | Using index |
+----+-------------+-------+------------+-------+---------------+--------+---------+------+--------+----------+-------------+

range     Index range scan ( Secondary index :>,<,<=,>=,or,like,in,!= On the primary key column , these type All are range)

ref      Auxiliary index equivalent query 

eq_ref    When multi table join query ,on The condition column of is a unique index or primary key 
const/system    Primary key or unique key equivalent query 
NULL    When no data can be found, it will display NULL

Extra: NULL

using filesort This is an unreasonable index design , It's going to be order by,group by  And where Joint index of 
where A group by B order by C
 Indexes :idx_A_B_C(A,B,C)

 Insert picture description here
Interview questions :
There is a select Statement is usually very fast when querying , Suddenly one day it was very slow , What will be the reason ?

1、 Index failure , The statistics are not true , Index has the ability of self maintenance , When the table content changes frequently , Index failure may occur , General deletion or reconstruction
2、 Lock conflict , All the resources have been exhausted due to the lock problem , Nothing can be done

7、 ... and 、 Storage engine

1、InnoDB Engine introduction and engine classification

1、 Introduce

Be similar to linux The file system in the system , The storage engine works on tables , That means , Different tables can have different storage engine types

2、 function

Data reading and writing
Data security and consistency
Improve performance
Hot backup
Automatic fault recovery
High availability support

3、oracle Of mysql species

show engines; You can look at
master InnoDB and MyISAM The difference between

+--------------------+
| Engine             |
| CSV                |
| MyISAM             | 
| MEMORY             |
| ARCHIVE            |
| InnoDB              |     
+--------------------+

other mysql The engine of

PerconaDB : The default is XtraDB
MariaDB: The default is InnoDB

Other storage engines support

TokuDB
RocksDB
MyRocks
What these three storage engines have in common : The compression ratio is high , High data insertion performance

Interview questions :
How to view all... Under the entire database InnoDB Table and MyISAM Table of

mysql> select table_schema,table_name,engine from information_schema.tabre engine = "InnoDB";

4、 Storage engine operation class commands
Use select Confirm the session storage engine

mysql> select @@default_storage_engine;
+--------------------------+
| @@default_storage_engine |
+--------------------------+
| InnoDB                   |
+--------------------------+

Default storage engine settings

vim /etc/my.cnf
[mysqld]
default_storage_engine=InnoDB

Expand :
Modify online mysql Parameters

Session level :set default_stroage_engine=myisam, Only the current session is affected
Global level :set gloabl default_stroage_engine=myisam, Does not affect the current session , Only new sessions are affected .
The above two methods , It will fail after restart , Unless the parameter is added to /etc/my.cnf In the document .

2、InnoDB Physical storage structure

ll /data/mysql/data
ib_buffer_pool   Buffer pool 
ibdata1: System data dictionary information ( What table of statistical information , What is the status of the table ),undo( Roll back ) Data such as table spaces 
ib_logfile0:redo( redo ) Log files , Transaction log file 
ib_logfile1:redo Log files , Transaction log file 
ibtmp1: Temporary table space disk location , Store temporary tables 
frm : Store the column information of the table , Name , Column data type 
ibd: Data rows and indexes of tables  - Also called table space 

surface =ibd+frm+ibdata1
mysql Storage engine logs for :

redo log:ib_logfile0,ib_logfile1 Redo log
undo log:ibdata1,ibdata2( Stored in a shared table space ), Rollback log
A temporary table :ibtmp1, Doing it join union Operation produces temporary data , Automatically delete after use

Table by ibd+frm+ibdata1 form , The following commands can delete a tablespace :ibd

alter table t1 discard tablespace;

take t1 Tabular ibd Copy as ibd.bak, After execution of the above order ibd The file is gone , At this point, if you put ibd.bak Copy as ibd It's no use , Because the indexes and other data have been deleted in the database , To recover, you need to import the following commands , Be careful to modify ibd The authority of is mysql

alter table t1 import tablespace;

3、 The nature of transactions

What is the role ?

Business is to ensure DML Statement as a unit ACID Characteristics of , Affected DML sentence (insert,update,delete, Part of the select), The following characteristics are affected
Atomicity : All statements are executed successfully or cancelled as a unit , There's no intermediate state ( Hand out red envelopes , Two article - and + Statements should be executed at the same time )
Uniformity : If the database is in a consistent state at the beginning of the transaction , Consistency will be preserved during the execution of the transaction (a Account 100 block ,b Account 0 element ,a to b Hair 50, Finally, the sum of the two is 100)
Isolation, : Transactions do not interact
persistence : After the transaction completes successfully , All changes made will be accurately recorded in the database , All changes are not lost

4、 The life cycle of a transaction

1、 from begin Start , To commit end

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from stu;
+-----+----------+------+------+
| sno | sname    | sage | ssex |
+-----+----------+------+------+
|   1 | zs       |   16 | f    |
|   2 | liyu     |   23 | m    |
|   3 | xixi     |   12 | f    |
|   4 | qianqian |   22 | f    |
+-----+----------+------+------+
4 rows in set (0.00 sec)

mysql> delete from stu where sno>3;
Query OK, 1 row affected (0.00 sec)

mysql> delete from stu where sno=1;
Query OK, 1 row affected (0.01 sec)

mysql> select * from stu;
+-----+-------+------+------+
| sno | sname | sage | ssex |
+-----+-------+------+------+
|   2 | liyu  |   23 | m    |
|   3 | xixi  |   12 | f    |
+-----+-------+------+------+
2 rows in set (0.00 sec)

mysql> commit;
Query OK, 0 rows affected (0.01 sec)
 If you don't press commit, Then open another window to see 4 statement ;
 In another window begin,delete Can not be done during operation , You have to wait for another window to finish , This is the isolation of transactions .

2、 Rollback of transaction ,rollback

mysql> delete from stu where sno=2;
Query OK, 1 row affected (18.43 sec)

mysql> select * from stu;
+-----+-------+------+------+
| sno | sname | sage | ssex |
+-----+-------+------+------+
|   3 | xixi  |   12 | f    |
+-----+-------+------+------+
1 row in set (0.00 sec)

mysql> rollback;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from stu;
+-----+-------+------+------+
| sno | sname | sage | ssex |
+-----+-------+------+------+
|   2 | liyu  |   23 | m    |
|   3 | xixi  |   12 | f    |
+-----+-------+------+------+
2 rows in set (0.00 sec)

3、 Automatic submission
If you type in begin, But never commit either rollback, Has been occupying resources , Due to the isolation of transactions , No one else can do it , therefore mysql I came up with the following ideas

Don't write begin, direct writing DML sentence , The system will directly give you commit 了

5、 Lock introduction

Locking means , It provides the function of isolation , Need to cooperate with undo+ Isolation levels work together

InnoDB Lock level of : Row-level locks , Change a line , Will lock a certain row , Others cannot modify this row of data at the same time . Involves common wait and deadlock .

6、InnoDB Core parameters

1、 One of the double one standards :innodb_flush_log_at_trx_commit=1
effect : Controlled redo buffer Brush strategy , It's a safety parameter ,5.6 Default parameters for version

mysql> select @@innodb_flush_log_at_trx_commit;
+----------------------------------+
| @@innodb_flush_log_at_trx_commit |
+----------------------------------+
|                                1 |
+----------------------------------+

1: Every time a transaction is committed , Will immediately brush down redo To disk (redo buffer-----> Every business ----->os buffer-----> disk )
0: When the transaction commits , Do not write the log immediately , It's going to be... Every second log buffer The data in is written to the file system cache and seconds fsync Disk once
2: Each transaction commit causes a write to the file system cache

原网站

版权声明
本文为[I love Qianxi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280515160283.html