Home >Database >Mysql Tutorial >How to modify the table structure of MySQL database online
Recommended learning: mysql video tutorial
Before modifying the table structure , let’s first look at possible problems.
MySQL has a lock called MDL metadata lock. When the table is modified, this lock will be automatically added to the table, that is, it will not You need to use it explicitly yourself.
Reading and reading are not mutually exclusive, reading and writing, writing and writing are mutually exclusive, so
And once the MDL is locked, it will only be released after the currently requested transaction is submitted. If it is a long transaction, or the amount of online data is large, the table structure will be modified by default. Without the MDL write lock, it will be time-consuming and block other subsequent requests.
Imagine a scenario where A(select), B(alter), C(select), D(select)...are requests for the same MySQL table in sequence. These requests will Form a queue.
When A (select) acquires the MDL read lock of the table, it will block B (alter), because B needs to add the MDL write lock. After B is blocked, it will cause other people in the waiting queue to All requests are blocked, eventually causing MySQL's available connections to be exhausted, request timeouts and other problems.
In view of the above MDL lock, we know that altering the structure of the table will block other normal requests, so the modification operation should be placed in a non-stop It is done during peak business hours, usually between 2 and 4 in the morning.
Specific steps:
The problem with the above solution is that when the amount of data is large, it takes time to import all the data. During this process, the service is inaccessible .
Improvement:
Create a new table A_new, which has several more fields than the original table. Subscribe to the original table A through data subscription. The data in the online table A is synchronized to the newly created table A_new. This process will continue, and table A can be added, deleted, modified, and checked during this process. There will always be a moment when the data of the two tables are completely synchronized. Yes, there is no difference in the data. At this time, the original table name A is modified, and the new table A_new is modified to the original table A. This operation is a short operation and can be completed instantly without much impact.
Advantages and disadvantages:
Recommended learning: mysql video tutorial
The above is the detailed content of How to modify the table structure of MySQL database online. For more information, please follow other related articles on the PHP Chinese website!