当前位置:网站首页>Notes on MySQL core points

Notes on MySQL core points

2022-06-11 08:53:00 JUST DO YOU LIKE

Conditions of the query

-- 1、 Relational operator :> < >= <= = <> ( It can also be used. !=, It is a kind of tolerant treatment , Don't suggest )
select count(last_name),last_name,first_name FROM employees WHERE salary<>20000    -- The aggregate function can only display one line
-- 2、 Filter by logical expression :and or
-- 3、 Range expression :between and,not between and
-- 4、 Determine set :in,not in
-- 5、 Character matching :like,not like
-- 6、 Null value :is null ,is not null

select last_name,first_name,manager_id FROM employees limit 0,3

select last_name,first_name FROM employees WHERE commission_pct is NULL

nested queries

-- 1、in

Uncorrelated subqueries : Subqueries do not depend on parent parameters

select * from student where sdep in(select * from sdept)

-- 2、 Single relation subquery , That is, the subquery will only return one record

Correlation subquery : Child queries depend on parent parameters

select sno,sname,grade 
from sc x
where grade >= (
    select AVG(grade) from sc y 
    where x.sno = y.sno 
)

-- 3、(any、all) Multi relation subquery , That is, the subquery will return multiple records

Related relational function formats :>any、>all、<any、<all、>=any、>=all、<=any、<=all、=any、=all、<>any、<>all

select sname,sage 
from student 
where sdept<any(
    select sage 
    from student 
    where sdept = 'cs'
)

-- 4、exists Subquery : There is returned true, conversely false, such as select *, As long as there is one record, it will return true

select sname 
from student 
where exists(
    select * 
    from sc 
    where sno = student.sno and cno = '1'
)

Set query

-- 1、union: Combine

select * from student where sdept = 'cs'
union
select * from student where sage <= 19

-- 2、intersect: intersection

select * from student where sdept = 'cs'
intersect
select * from student where sage <= 19

-- 3、except: Difference set , As follows, the Department is cs Of 19 Students over years old

select * from student where sdept = 'cs'
except
select * from student where sage <= 19

Derived table query

select sno,cno
from sc,(select sno,avg(grade) from sc group by sno)
as avg_sc(avg_sno,avg_grade) // A temporary table 
where sc.sno = avg_sc.avg_sno and sc.grade >= avg_sc.avg_grade

Sort query

--  Sort query , In addition, let's talk about the query order , First from surface , then where Conditions of the query , next select, Last order by 
select last_name,first_name,salary FROM employees WHERE commission_pct is NULL ORDER BY salary,first_name DESC
select last_name,first_name,salary FROM employees WHERE commission_pct is NULL ORDER BY first_name DESC,salary

Common function

-- Common function : Character functions 、 Mathematical functions 、 Date function 、 Process control functions 、 Custom function
-- 1、 Character functions
-- Splicing :CONCAT(str1,str2,...)    
select CONCAT(first_name,last_name,IFNULL(commission_pct,"null")) FROM employees
-- Get the byte length :LENGTH(str)
select LENGTH(first_name) FROM employees
-- Get character length :CHAR_LENGTH(str)
select CHAR_LENGTH(first_name) FROM employees
-- Intercept substring :SUBSTR(str FROM pos FOR len)
SELECT SUBSTR(' Zhangsanfeng fell in love with Guoxiang ',1,3)
-- Replace data :INSERT
select INSERT('mysql',1,2,'MY')
-- Get the index of the first occurrence of the character :INSTR(str,substr)
select INSTR(' The people's Republic of China and the Republic of China ',' The Chinese ')
-- Remove the space before and after :TRIM([remstr FROM] str)
select TRIM('   virtual   bamboo  ')
-- Remove the characters specified before and after :TRIM([remstr FROM] str)
select TRIM('xy' FROM 'xyxxx virtual xx bamboo xxxxxy')
-- Remove the left side / Specify the character on the right
select LTRIM('     virtual   bamboo  ')
select RTRIM('     virtual   bamboo  ')
-- Return string str Leftmost / Dexter len Characters :LEFT(str,len)/RIGHT(str,len)
select LEFT('str',2)
select RIGHT('str',2)
-- LPAD/RPAD padding-left / Right fill , The results are the same, but in different directions
select LPAD(' mu wanqing ',3, 'a')
select RPAD(' mu wanqing ',10,'a')
-- UPPER/LOWER Case write
select UPPER('abcd')

-- Case study : Query the name of the employee table , Format required : The first character of the last name is capitalized , Other characters are lowercase , All characters of the name are capitalized , And between the last name and the first name _ Division , The last alias is OUTPUT
select UPPER(SUBSTR(first_name,1,1)),first_name FROM employees
select LOWER(SUBSTR(first_name,2)),first_name FROM employees
select UPPER(last_name) FROM employees
select concat(UPPER(SUBSTR(first_name,1,1)),LOWER(SUBSTR(first_name,2)),'_',UPPER(last_name)) OUTPUT FROM employees

-- STRCMP(expr1,expr2) Compare
select STRCMP('A','a')
select STRCMP('B','a')
-- 2、 Mathematical functions
-- Absolute function :ABS(X)
select abs(-2.6)
-- Rounding up :CEIL(X)
select CEIL(1.09)
-- rounding
select ROUND(1.87123)
-- Round to three decimal places
select ROUND(1.87123,3)
-- truncation :truncate
select TRUNCATE(1.87,1)
select TRUNCATE(1.87,0)
-- Take the remainder :MOD(N,M)
select MOD(-10,3)
select 3/10
-- 3、 Date function
select NOW()
select CURDATE()
select CURTIME()
select DATEDIFF('2019-7-13','1998-7-16')
select DATE_FORMAT('2019-7-13 18:20:20','%Y year %m month %d Japan %H Hours %i minute %s second ')
select STR_TO_DATE('3/15 1998','%m/%d %Y')
select * from employees WHERE hiredate < STR_TO_DATE('3/15 1998','%m/%d %Y')

-- 4、 Process control
SELECT IF ( 100 > 9,
' good ',
' bad ' 
)

SELECT
    department_id,
    salary,
CASE
    department_id 
    WHEN 30 THEN
    1 
    WHEN 50 THEN
    2 ELSE 3 
    END result 
FROM
    employees

Aggregate functions / Statistics / Group function

-- polymerization / Statistical function

COUNT(DISTINCT expr,[expr...])
MAX(expr)
MIN(expr)
AVG([DISTINCT] expr)
SUM(expr)
-- Add : General inquiry count Direct use *, This means that as long as there is a field in the query line that is not null Even if it's on , Relatively fast
COUNT(*)

-- grouping
select count(*),salary from employees 
-- grouping +HAVING:having Is to filter the statistical function conditionally
select COUNT(*),AVG(salary) avg from employees GROUP BY salary HAVING avg>4000

Connect

1. Cartesian connection :

        select * from tableA,tableB...

2. Internal connection

        2.1. Internal connection :SELECT * FROM student INNER JOIN score ON student.studentno=score.studentno

        2.2. Equivalent connection : Based on Cartesian product , Add equivalent conditions :SELECT * FROM student, score WHERE student.studentno=score.studentno

        2.3. Unequal value connection : Equal value connection , Only the operators include >、>=、<=、<、!>、!< and <>.

        2.4. Natural join : Internal connection with de duplication function , For example, two tables have fields of the same name and type , Two columns of this field are generally displayed in the associated table query results , And natural connections can be de duplicated , Ensure that only one column is displayed :SELECT ... FROM ... NATURAL JOIN ... ON ...=...

3. External connection

        3.1. Left [ Outside ] Connect :select * from student LEFT JOIN score ON student.studentno=score.studentno

        3.2. Right [ Outside ] Connect :select * from student RIGHT JOIN score ON student.studentno=score.studentno

        3.3. Full connection :select * from student FULL JOIN score ON student.studentno=score.studentno

Example

1、 Simple two table query

use myemployees

select last_name,department_name FROM employees e,departments d

2、 Add filter

Check department number >100 Department name and city name

Query the name of the employee with bonus 、 Department name

The second character in the query city name is o Department name and city name of

3、 Add groups + Screening
Check the number of departments in each city
Query the Department name and leader number of each department with bonus and the minimum wage of the Department
Query the number of employees in the Department >10 The name of your department

4、 Add groups + Screening + Sort
Query the number of employees in the Department >10 The name of your department , And in descending order of department names
Query the number of employees and the name of each type of work , And in descending order

5、 Three meter connection
Case query employee name 、 City name

Common types

integer
tinyint smallint int bigint
floating-point
double(m,n) float decimal    m Indicates total length ,n Indicates the number of digits reserved after the decimal point
Character
char varchar text
Binary system , Used to store graphic data
blob
Date type
date     Format :yyyy-MM-dd 
time     Format :hh:mm:ss
timestamp     Format :yyyyMMdd hhmmss
datetime Format :yyyy-MM-dd hh:mm:ss

Six constraints

not null
default 
primary key
FOREIGN KEY
unique 
check

for example :create table sc(
    sno char(9) [not null,unique,PRIMARY KEY],
    cno char(4),
    grade SMALLINT,
    [PRIMARY key(sno,cno),]
    [FOREIGN KEY(sno) REFERENCES student(sno),]
    [check(grade<>0 and grade>60)]
)

Four big SQL sentence

1、DDL (database definition language)
Table creation
CREATE TABLE IF NOT EXISTS xxx;
Delete table
drop table if exists xxx [RESTRICT/CASCADE];
modify :ALTER TABLE Statement is used to add... To an existing table 、 Modify or delete columns ,.
1. ALTER TABLE table_name ADD column_name datatype
2. ALTER TABLE table_name DROP COLUMN  column_name
3. ALTER TABLE table_name ALTER COLUMN column_name datatype
4. ALTER TABLE table_name RENAME COLUMN column_name to newname
5. ALTER TABLE table_name RENAME to newname
Copy table
     Copy structure + data
    create table xxx select * from yyy
    create table xxx select * from yyy.column
     Copy structure
    create table xxx like yyy

2、DML(database manipulate language)

delete from tablename

update tablename set colume = newvalue where ...

insert into tablename values(...)

3、DQL

select * from tablename [lock on share mode|for update]

4、DCL

rollback、commit、grant...

Storage engine

innodb The default transaction is automatically turned on

1. InnoDB Support transactions ,MyISAM I won't support it , about InnoDB Every one of them SQL Languages are encapsulated as transactions by default , Automatic submission , This will affect the speed , So it's better to put more than one SQL Language is put in begin and commit Between , Make up a business ; 

2. InnoDB Support foreign keys , and MyISAM I won't support it . For one containing a foreign key InnoDB Table to MYISAM Will fail ; 

3. InnoDB Support primary key

4. InnoDB It's a clustered index , Use B+Tree As an index structure , Data files are and ( Primary key ) The indexes are tied together ( Table data file itself is by pressing B+Tree An index structure of an organization ), There must be a primary key , Indexing through the primary key is very efficient . And auxiliary ( It's not clustering ) The index requires two queries , First query to the primary key , Then query the data through the primary key .

5. 5.6 After version InnoDB It also supports full-text indexing

6. InnoDB Not only table locks but also row locks are supported

7. Innodb The stored files are frm、ibd, and Myisam yes frm、MYD、MYI

        Innodb:frm It's a table definition file ,ibd It's the structure + Data files

        Myisam:frm It's a table definition file ,myd It's a data file ,myi Is the index file

Business

show variables like '%auto%'
Turn off auto submit
set autocommit =0
Turn on manual transactions
start TRANSACTION
Write the of the transaction sql sentence
...
Commit or roll back ( If there is an uplink lock during execution )
commit or rollback

give an example
START TRANSACTION
select count(*) FROM departments
delete FROM departments where department_id = 1
select count(*) FROM departments
ROLLBACK

ACID: Atomicity 、 Uniformity 、 Isolation, 、 Permanence

1、 View the... Of the current session Isolation level :
select @@tx_isolation;
2、 Check the isolation level of the system :
select @@global.tx_isolation;
3、 Set the isolation level of the session , The isolation levels from low to high are :
set session transaction isolation level read uncommitted;
set session transaction isolation level read committed;
set session transaction isolation level repeatable read;
set session transaction isolation level serializable;
4、 Set the isolation level of the current system , The isolation levels from low to high are :
set global transaction isolation level read uncommitted;
set global transaction isolation level read committed;
set global transaction isolation level repeatable read;

【 notes :】mysql The default transaction level is 'REPEATABLE-READ', and Oracle and SQL Server yes READ_COMMITED

lock

SQL Statements are read and write operations in the final analysis , So only the read-write lock , The read-write lock is divided into row lock and table lock according to the locking range :

Row lock ( It's a read-write lock 、 It's a reentrant lock 、 It's a line lock / Clearance lock 、 It's a pessimistic lock )

     The disadvantage of row lock : Spending big ; Lock the slow ; A deadlock occurs

     The advantages of row locks : The granularity of locks is fine ( There are too many locks , The finer the more , The thicker the less ), The probability of lock conflict is low ; The ability to handle concurrency is strong

     Locking method : Automatic locking . about UPDATE、DELETE and INSERT sentence ,InnoDB An exclusive lock will be automatically added to the involved data set ; For ordinary SELECT sentence ,InnoDB No locks ; Of course, we can also show the lock :

        1、 read / Shared lock :select * from tableName where … + lock in share more

        2、 Write / An exclusive lock / Exclusive lock :select * from tableName where … + for update、UPDATE、DELETE and INSERT

     Locking time :SQL When executing a statement
    
     Unlocking time : If you have any business, you should arrive at commit/rollback Unlock when , No transaction completed SQL Unlock when

Table locks ( It's a read-write lock 、 It's a watch lock 、 It's a reentrant lock 、 It's a pessimistic lock )

    The disadvantage of watch lock : Concurrency is slow , The possibility of lock conflict is high
    
     The advantages of watch lock : The lock granularity is coarse , Less resources
    
     Generally, the watch lock is locked / Unlocking time :

        1、 read / Shared lock (S lock ):lock/unlock table Table name read

        2、 Write / An exclusive lock (X lock ):lock/unlock table Table name write
        
        3、 Unlock all :unlock tables, It must be unlocked manually , Unlike row lock , Automatically unlock after a transaction or statement ends
        
        4、 Table lock compatibility ( Table level S、X Compatibility )
        
                        S      X
            S       +      -
            X          -      -

Intent locks ( It's a read-write lock 、 It's a watch lock 、 It's a reentrant lock 、 It's a pessimistic lock ).

           1、 effect Only to resolve row lock and table lock conflicts : Such as transaction A With a row lock , Business B I want to lock my watch ,B You need to traverse each row to see if there is a row lock , And when we find out the affairs A It has taken a long time to lock the rows of , In order to solve this problem, intention lock is introduced , An intent lock is a table level read / write lock , Add an intention lock before adding a bank lock , It's a business B To add a table lock, you only need to check whether a table lock or an intention lock is added , Efficiency improvement ;

           2、 Intentional locks do not worry about the conflict between row locks : If both transactions apply for an intent lock , The intentional locks are compatible with each other ( namely IS and IX、IS and IS、IX and IS They are compatible with each other ), because 1 It has been said in that the lock will be added before the bank lock is added , So currently, row lock conflicts actually occur , The row lock mechanism can solve the concurrency problem , There is no need to worry about intentional lock
            
           3、 Intent locks IS、IX And watch level locks S and X The conflict of :
        
                            IS     IX      S    X
                IS         +      +      +     -
                IX         +      +      -      -
                S          +      -       +      -
                X          -      -        -       -
        
         locked / Unlocking time :MySQL The intention lock is automatically added before the bank lock is added , If there is a transaction during unlocking commit/rollback Unlock when , If there is no transaction SQL Release the lock at the end of the statement
                    
         Read-write lock : Intent locks are table level read / write locks , Divided into intention sharing lock (IS lock )、 Intent exclusive lock (IX lock ), As long as there is s Lock on is lock , share s lock , Isolation x lock 、ix lock

        Locking time :SQL When executing a statement
    
        Unlocking time : If you have any business, you should arrive at commit/rollback Unlock when , No transaction completed SQL Unlock when

cache

MySQL cache https://zhuanlan.zhihu.com/p/55947158#:~:text=MySQL%E8%83%BD%E5%A4%9F%E7%BC%93%E5%AD%98%E7%9A%84%E6%9C%80%E5%A4%A7%E6%9F%A5%E8%AF%A2%E7%BB%93%E6%9E%9C%EF%BC%8C%E6%9F%A5%E8%AF%A2%E7%BB%93%E6%9E%9C%E5%A4%A7%E4%BA%8E%E8%AF%A5%E5%80%BC%E6%97%B6%E4%B8%8D%E4%BC%9A%E8%A2%AB%E7%BC%93%E5%AD%98%E3%80%82,%E9%BB%98%E8%AE%A4%E5%80%BC%E6%98%AF1048576%20%281MB%29%E5%A6%82%E6%9E%9C%E6%9F%90%E4%B8%AA%E6%9F%A5%E8%AF%A2%E7%9A%84%E7%BB%93%E6%9E%9C%E8%B6%85%E5%87%BA%E4%BA%86%E8%BF%99%E4%B8%AA%E5%80%BC%EF%BC%8CQcache_not_cached%E7%9A%84%E5%80%BC%E4%BC%9A%E5%8A%A01%EF%BC%8C%E5%A6%82%E6%9E%9C%E6%9F%90%E4%B8%AA%E6%93%8D%E4%BD%9C%E6%80%BB%E6%98%AF%E8%B6%85%E5%87%BA%EF%BC%8C%E5%8F%AF%E4%BB%A5%E8%80%83%E8%99%91%E5%9C%A8SQL%E4%B8%AD%E5%8A%A0%E4%B8%8ASQL_NO_CACHE%E6%9D%A5%E9%81%BF%E5%85%8D%E9%A2%9D%E5%A4%96%E7%9A%84%E6%B6%88%E8%80%97%E3%80%82
MySQL Cache application scenarios https://www.jianshu.com/p/63ce65e4dc23

in general MySQL Cache uses less , In big data volume 、 Minor concurrency 、 Very suitable for systems with small changes , Use distributed cache for high concurrency

Indexes

With innoDB For example , Passed while creating the table B The tree implements the clustering index of the primary key , Therefore, when querying, you want to play B The fast query power of the tree must be queried with the primary key , But not so SQL All queries are based on fields other than the primary key , Therefore, it is necessary to build a non clustered index with common query fields

Index add

1 Add index to new table

① General index

create table t_dept(
    no int not null primary key,
    name varchar(20) null,
    sex varchar(2) null,
    info varchar(20) null,
    index index_no(no)    // Index based colume Set index name , such as no, Then the naming format is index_no
  )

② unique index

create table t_dept(
       no int not null primary key,
       name varchar(20) null,
       sex varchar(2) null,
       info varchar(20) null,
       unique index index_no(no)
     )

③ Full-text index

create table t_dept(
       no int not null primary key,
       name varchar(20) null,
       sex varchar(2) null,
       info varchar(20) null,
       fulltext index index_no(no)

④ Multi column index

create table t_dept(
       no int not null primary key,
       name varchar(20) null,
       sex varchar(2) null,
       info varchar(20) null,
       key index_no_name(no,name)
     )

2 Add an index to the built table

① General index

create index index_name          //index_name Is the index name 
             on t_dept(name);    //t_dept Is the name of the table 

② unique index

create unique index index_name
              on t_dept(name);

③ Full-text index

create fulltext index index_name
              on t_dept(name);

④ Multi column index

create index index_name_no
               on t_dept(name,no)

3 Add indexes by modifying tables

① General index

alter table t_dept
          add index index_name(name);

② unique index

alter table t_dept
            add unique index index_name(name);

③ Full-text index

alter table t_dept
           add fulltext index_name(name);

④ Multi column index

alter table t_dept
              add index index_name_no(name,no);

  The following situations are suitable for index creation

  1. On columns that often need to be searched , Can speed up the search .

  2. On the column as the primary key , Force the uniqueness of the column and organize the data in the table .

  3. On columns that are often used to join two tables , These columns are mainly some foreign keys , Can speed up the connection .

  4. Create indexes on columns that often need to be searched by range , Because the index is sorted , Its specified range is continuous .

  5. Create indexes on columns that often need to be sorted , Because the index is sorted , In this way, the query can take advantage of index sorting , Speed up sorting query time .

  6. It is often used in WHERE Create an index on the column in clause , Speed up the judgment of conditions .

The following situations are not suitable for creating an index

  1. There are too few records .

  2. Often add or delete tables .

  3. Duplicate and evenly distributed table fields , Therefore, you should only index the most frequently queried and frequently sorted data columns ( If a data column contains many duplicate contents , Indexing it doesn't have much practical effect ) Index failure scenario https://blog.csdn.net/Dxy1239310216/article/details/121679668

tuning

         Write effective sql It also needs skill , Know how to avoid index invalidation

slow SQL tuning https://blog.csdn.net/flycp/article/details/108084388?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165321001516781483780109%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165321001516781483780109&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-108084388-null-null.142%5Ev10%5Econtrol,157%5Ev4%5Econtrol&utm_term=%E6%85%A2SQL%E8%B0%83%E4%BC%98&spm=1018.2226.3001.4187

index tuning https://zhuanlan.zhihu.com/p/61687047

Small tables drive large tables https://blog.csdn.net/fly_miqiqi/article/details/90348800

stored procedure

stored procedure https://blog.csdn.net/qq_36777191/article/details/104171953

Storage function

trigger https://blog.csdn.net/qq_36777191/article/details/104176504

trigger

trigger https://blog.csdn.net/qq_36777191/article/details/104190013

Three logs

        namely redolog、binlog、undolog

        redolog

        1、 yes innoDB Log , Physical storage ;

        2、 The task is to ensure data consistency after downtime and restart ;

        3、 Recording transactions , When the transaction ends, it will not be flushed to disk immediately , But through redo buffer It was recorded that redolog, Then, it will be brushed asynchronously ibd;

        4、redolog write in ibd That part of the data is equivalent to expired ,redolog Will overwrite that part of the data with new data , Therefore redolog Logs are reusable persistent files

        binlog

        1、 yes MySQL Log , Logical storage ;

        2、 The task is log analysis , Master slave synchronization , Data recovery ;

        3、 Record data changes , There are ways to record row、statement and miexd

                row: For example, a certain field in a certain row becomes ***, The advantage is that the records are detailed , Disadvantages: large resources

                statement: Namely SQL sentence , Advantages save resources , Disadvantages: in the master-slave mode, functions are easy to be inconsistent , such as now(),uuid()

                mixed: Use... For automatic selection row still statement

        redolog and binlog The difference between

        1、redo log Is in InnoDB The storage engine layer generates , and binlog yes MySQL From the top of the database , And binary logging is not just for INNODB Storage engine ,MySQL Any storage engine in the database will generate binary logs for changes to the database .

        2、 The two kinds of log records have different content forms .MySQL Of binlog It's a logical log , Its record is corresponding to SQL sentence . and innodb Redo logs at the storage engine level are physical logs .

        3、 The two kinds of logs and records are written to disk at different time points , The binary log is written only once after the transaction commit is completed . and innodb The redo log of storage engine is continuously written in the process of transaction , And the log is not written in the order of transaction commit .

         4、binlog After full write or restart , There will be new binlog file , and redo log It's recycling .

        5、binlog As data analysis , Data recovery , Master slave synchronization , and redo log I'll be involved ibd Data persistence process , The purpose is to recover data in case of abnormal downtime or media failure . 

binlog Application in master-slave replication

 

It can be seen that redolog Participated in ibd Data persistence of ,redlolog Is very important  

        undolog        

        1、 Realize the atomicity of transactions :undo log Can be used to implement atomicity of transactions , If there are some special circumstances in the transaction process , such as sql Errors, etc , You have to roll back (rollback) operation ,mysql You can use it undo log Restore the data before the transaction starts

        2、 Realize multi version concurrency control (MVCC):undo log stay MySQL InnoDB Concurrent storage is used to implement version control engine , Before the transaction is committed ,undo Logs can be used in high concurrency situations , Snapshot reading is performed for other concurrent transactions

Good article recommends

  binloghttps://blog.csdn.net/Allenzyg/article/details/106446992  redolog Function and principle of https://blog.csdn.net/qq_42773863/article/details/120988441?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165324292716782425142146%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=165324292716782425142146&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-4-120988441-null-null.142%5Ev10%5Econtrol,157%5Ev4%5Econtrol&utm_term=redolog+ibd&spm=1018.2226.3001.4187redolog and binlog The difference between https://blog.csdn.net/wanbin6470398/article/details/81941586

undologhttps://blog.csdn.net/u014427391/article/details/109022361
Three logs https://javaguide.cn/database/mysql/mysql-logs.html#%E5%89%8D%E8%A8%80         colony

         Cluster is n Lord m From the layout of , In general, the logic of master-slave replication lies in the host write , Read from machine . The general logic of the development from single architecture to cluster architecture :

  1. Put the monomer architecture ibd Copy to the extended machine ,
  2. Host settings binlog Record events ,
  3. binlog Data synchronization to the slave , From machine record to relaylog, then flush To the slave disk

        relay log

         We translate it into Chinese , It is generally called relay log , Usually it's in MySQL The slave node of the master-slave synchronous read-write separation cluster is enabled . The primary node generally does not need this log .

        master The master node binlog to slave From behind the node , Written relay log in , From node's slave sql The thread from relaylog Read the log in and apply it to slave From the local node . From the server I/O The thread reads the binary log from the primary server and logs it to the slave server local file , then SQL The thread will read relay-log The contents of the log are applied to the slave server , So that the data of the slave server and the master server are consistent .

         Its function can be referred to the following figure , As you can see from the picture , It is a temporary log file for mediation , Used to store data from master The nodes are synchronized binlog Log contents , Its contents and master Node binlog The contents in the log are consistent . then slave From this node relaylog The data read from the log file is applied to the database , To realize master-slave replication of data .

  Good article recommends

Master slave copy https://blog.csdn.net/qq_21153619/article/details/81529880

Master slave copy https://blog.csdn.net/weixin_30539317/article/details/113281081?ops_request_misc=&request_id=&biz_id=102&utm_term=%E7%94%9F%E4%BA%A7%E7%8E%AF%E5%A2%83%20MySQL%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-0-113281081.142%5Ev10%5Econtrol,157%5Ev4%5Econtrol&spm=1018.2226.3001.4187relaylog and binlog Realization MySQL The principle of master-slave synchronization https://blog.csdn.net/javaanddonet/article/details/112596148

原网站

版权声明
本文为[JUST DO YOU LIKE]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110841562225.html