MySQL basic knowledge summary

**Transaction**
is the basic unit of concurrency control. The so-called transaction, it is a sequence of operations,

The four characteristics of transaction (ACID)
atomicity: refers to the transaction is a smallest unit, can not be separated, and become a whole. Either all transactions are executed, or all are not executed, and there is no intermediate state.
Consistency: Means that the methods in the transaction either succeed at the same time or are not successful. For example, A to B transfers money, either all succeed or all fail.
Isolation: Many transactions can be started at the same time in the MySQL database, but they are separated from each other, that is, they do not affect each other. Guaranteed by locks.
Persistence: When a database record is successfully inserted, the database must ensure that a piece of data is permanently written to the database disk.

Concurrency
of transactions 1. Concurrency of transactions and simultaneous execution of multiple transactions

Issues caused by transaction concurrency
1. Dirty writes The
data in transaction 2 is modified but not yet committed.
Transaction 1 modifies the data in transaction 2, and
then transaction 2 commits the data.
Then transaction 1 rolls back,
causing the modification in transaction 2 to be overwritten and rolled back

2. Dirty read The
data in transaction 2 is modified but not yet committed.
Transaction 1 reads the data in transaction 2 and commits it.
Transaction 2 then rolls back,
causing transaction 1 to read non-existent data.

3. Non-repeatable reading
means that repeated reading will cause problems. Transaction 1 under the same conditions, the data read at the current time is inconsistent with the data read at the next time, that is, there is another transaction between the two times that has modified the data.

4. Phantom reading
means that transaction 1 will read more rows of data at the next moment than the current moment under the same conditions, which seems to be an illusion, because there are other transactions that add data between these two moments.

Transaction isolation levels, each level will cause any problem
isolation level of the transaction: read uncommitted, read committed, repeatable read, submit the serial
read uncommitted: there will be dirty read, to write dirty, non-repeatable read, phantom read
read Submitted: non-repeatable reading and phantom reading
will occur Repeatable reading: phantom reading will occur
Serial submission: the above problems will not occur

Which level of mysql default is
repeatable read

What kind of locks does mysql have?
1. A lock is a mechanism for a computer to coordinate multiple processes or threads to concurrently access a certain resource.
2. Various operations of the lock, including obtaining the lock, checking whether the lock has been released, and releasing the lock.
Others:
3. mysql locks are optimistic, pessimistic, shared, exclusive, row, and table locks.
Shared locks (read locks): other transactions can be read but not written.
Exclusive lock (write lock): other transactions cannot read or write.
Divided by strength: table-level lock, page lock, row-level lock.
There are table locks and row locks by default.
Table-level locks: low overhead and fast locking; no deadlocks; large locking granularity, the highest probability of lock conflicts, and the lowest concurrency.
Row-level locks: high overhead and slow locking; deadlocks will occur; locking granularity is the smallest, the probability of lock conflicts is the lowest, and the concurrency is the highest.

mysql pessimistic lock and optimistic lock
1, pessimistic lock believes that concurrency conflicts will always occur, so data needs to be locked during the entire data processing process.
Pessimistic lock: It is more suitable for scenarios where write operations are frequent. If a large number of read operations occur, locks will be performed every time they read, which will increase the overhead of a large number of locks and reduce the throughput of the system.
Shared locks, also known as read locks, are a type of pessimistic lock that can be viewed but cannot be modified or deleted.

2. Optimistic lock believes that no concurrency conflicts will occur, but when updating, it will judge whether others have updated the data during this period.
It is more suitable for scenarios where read operations are frequent. If a large number of write operations occur, the possibility of data conflicts will increase. In order to ensure data consistency, the application layer needs to constantly reacquire data, which will increase a large number of The query operation reduces the throughput of the system.

How to add exclusive lock when select?
Lock conflicts and deadlocks
1. A deadlock is an endless loop of locks between two or more transactions/requests.
2. Lock conflict: A session holds a write lock for a certain resource (such as data with id=1), and another seession just needs to request a write lock for the same data, and it must be blocked until the previous session is released. Until the lock is reached, I generally call it "dead lock" or "long wait for lock".

**What is the difference between the three common storage engines in mysql? **
1, InnoDB
2, MyISAM
3, MEMORY

MySQL's MyISAM and InnoDB storage engines are applicable at transaction and lock levels, and their respective applicable scenarios?
What is the order in which the different elements of the query statement (where, join, limit, group by, having, etc.) are executed?
Summarize the following order: My (W) brother (G) is (SH) even (O) like join where group by limit
W(where)->G(Group)->S(Select)->H(Having)-> O (Order)
1. Execute where xx to filter the entire table data and return the first result set.
2. Use group by grouping for the first result set, and return the second result set.
3. Execute select xx for each group of data in the second result set, and execute it several times for several groups, and return the third result set.
4. Execute having xx for the third set to filter, and return the fourth result set.
5. Sort the 4th result set.
6, limit

What is a temporary table and when is it deleted? A
temporary table is similar to an entity table, except that during use, the temporary table is stored in the system database tempdb. When we no longer use the temporary table, the temporary table will be automatically deleted.

**mysql index**
1. Index is actually a data structure that can help us quickly retrieve data in the database.
2. MySQL has two main structures: Hash index and B+ Tree index

What are the advantages and disadvantages of
indexing ? The advantages of indexing: 1. Natural sorting. 2. Quick search.
Disadvantages of index: 1. Take up space. 2. Reduce the speed of updating the table.
Why it takes up space: Because indexing will organize the sorted data into B-trees and put them on disk.

What is the difference between a clustered index and a non-clustered index?
Just like looking up a dictionary,
Pinyin retrieval is a clustered index; stroke retrieval is a non-clustered index. The
content of the text is sorted and stored according to a specific dimension, and this specific dimension is the clustered index; the
non-clustered index items are stored in order, but the content corresponding to the index items is random Stored

The difference between mysql B+Tree index and Hash index?
sql query statement to determine which type of index to create? How to optimize the query?
What is the difference between a non-relational database and a relational database, and what are the advantages?
1. Relational databases generally have a fixed table structure, and non-relational databases are document-based, with a storage mechanism of KV key-value pairs.
2. Non-relational databases are faster to read and write than relational databases.
3. Non-relational databases have better scalability.
4. Relational databases require consistency. Non-relational databases have no strict requirements.

Three paradigms of database, design data table according to a certain scene?
7 problems of database read-write separation, master-slave replication, master-slave replication analysis?
Use explain to optimize sql and index?

**How ​​to solve MySQL slow query? **
Check the slow query log to find the reason for the slow query, see if it is an index problem, and if the index is wrong.
Optimize query statements to avoid joins of more than three tables, etc.
Can subqueries be used to reduce the number of queries?
For a large amount of data, the method of sub-database and sub-table is adopted.

What are inner joins, outer joins, cross joins, Cartesian products, etc.?
Inner join:
select * from a
inner join b
on a.id=b.parend_id
left join:
select * from a
left join b
on a.id=b.parend_id
right join
select * from a
right join b
on a.id= b.parend_id

What are the usage scenarios of varchar and char?
Char uses a fixed length with a specified length to represent a string of fields.
Varchar(M) is a more flexible data type than char. It is also used to represent character data, but varchar can store variable-length strings.

mysql high concurrency environment solution?
The transaction recovery mechanism when the database crashes
REDO log and UNDO log
REDO in order to redo the information saved in the data page (page) change, used to restore
UNDO in order to undo the information saved in the data record (tuple) change, used to roll back the transaction

1. CONCAT(A, B)-concatenate two string values ​​to create a single string output. Usually used to combine two
or more fields into one field.
2. FORMAT(X, D)- Format the effective digits from X to D.
3. CURRDATE(), CURRTIME()-returns the current date or time.
4. NOW ()-returns the current date and time as a value.
5. MONTH(), DAY(), YEAR(), WEEK(), WEEKDAY()-
Extract the given data from the date value.
6. HOUR(), MINUTE(), SECOND()-extract the given data from the time value.
7. DATEDIFF (A, B)
-to determine the difference between two dates, usually used to calculate age 8. SUBTIMES (A, B)-to determine the difference between two dates .
9. FROMDAYS (INT)-Convert integer days to date values.
The case
MySQL database is used as the storage of the publishing system, with an increment of more than 50,000 entries a day, and it
is expected to be operated and maintained for three years. How to optimize
1. A well-designed database structure allows partial data redundancy, avoids join queries as much as possible, and improves efficiency. 
2. Select the appropriate table field data type and storage engine, and add indexes appropriately.
3. Separation of master and slave for MySQL library.
4. Find regular sub-tables, reduce the amount of data in a single table and improve query speed.
5. Add caching mechanisms, such as memcached, apc, etc.
6. Generate static pages for pages that are not frequently changed.
7. Write high-efficiency SQL. For example, SELECT * FROM TABEL is changed to SELECT field_1, field_2, field_3 FROM TABLE.
Lock optimization strategy
1, read-write separation
2, segmented lock
3, reduce lock holding time
4, multiple threads try to go in the same order Obtaining resources cannot make the lock granularity too fine, otherwise there may be too many threads to lock and release the number of times, but the efficiency is not as good as adding a large lock at a time.

Guess you like

Origin blog.csdn.net/jassyzhen/article/details/115299980