高性能MySql进化论(五):提速Alter Table 在系统的日常维护中,经常需要对表结构进行更新,例如添加/删除一个字段,改变一个VARCHAR的字段长度等等。MySQL针对这种修改表结构的处理方式是先创建一张新的结构的表,接着会通过执行Insert语句将旧表的内容插入到
高性能MySql进化论(五):提速Alter Table在系统的日常维护中,经常需要对表结构进行更新,例如添加/删除一个字段,改变一个VARCHAR的字段长度等等。MySQL针对这种修改表结构的处理方式是先创建一张新的结构的表,接着会通过执行Insert语句将旧表的内容插入到新表中,最后删除整张旧表。这种处理方式在数据量比较小的时候,不会有什么问题,可是当数据量很大的时候可能需要很多时间来处理该过程。
执行一个更新表结构的操作花费了几个小时的时间,这是无法忍受的。如果你用的是5.1之前的版本的话,还会在执行表结构更新是数据库往往是停止服务的,幸好在最新的版本中这个问题得到了改善
如果在进行表结构更新的时候你采用了恰当的方法,也并不是所有的更新操作会占用你很久的时间。
例如 你想更新用户表的默认密码为“666666”,通常采用的做法是
mysql> ALTER TABLE user
-> MODIFY COLUMN pwd VARCHAR NOT NULL DEFAULT ‘666666’;
通过SHOW STATUS你可以发现在执行这个操作的过程中进行了大量的Insert操作,当用户的数量很大时 例如百万,千万条的数据时,必然会消耗很多的时间。
可是如果你采用下边的方式来更新的话,时间会大大的缩短
mysql> ALTER TABLE user
-> ALTER COLUMN pwd varchar not null SETDEFAULT 5;
执行SHOW STATUS操作发现大量的插入操作不存在了,且时间也大大的缩短了(需要先进行FLUSH STATUS)
之所以可能缩短时间是因为
(1)表字段的默认值是放在表的frm(.frm:表结构文件 .MYD:表数据文件 .MYI:表索引)文件中
(2)ALTER COLUMN会更新frm文件,而不会涉及到表的内容
(3)MODIFY COLUMN会涉及到表数据的内容
从前面的列子可以看出如果操作的过程中只涉及到frm文件的改动的话,表结构的更新效率会大大的提高,但是很多时候在没有必要的时候mysql也会进行表的重建。如果你愿意承担风险,可以用修改frm文件的方式以达到提速修改表结的目的
(1) 更改字段的默认值
(2) 增加/删除字段的AUTO_INCREMENT属性
(3) 增加/删除/修改 ENUM的常量值。对于删除操作,如果有字段引用了这个常量值,则在删除后查询的结构为空字符串
下面以更新字段的默认值属性为例,分别通过使用ALTER COLUMN和修改frm文件的方式来提高修改表结构的效率
1 执行ALTER COLUMN
1.1 首先准备一张字典表
CREATETABLE IF NOT EXISTS dictionary (
id int(10) unsigned NOT NULLAUTO_INCREMENT,
word varchar(100) NOT NULL,
mean varchar(300) NOT NULL,
PRIMARY KEY (`id`)
);
1.2 插入一些测试数据
mysql>DELIMITER $$
mysql>DROP PROCEDURE IF EXISTS SampleProc$$
Query OK, 0rows affected, 1 warning (0.01 sec)
CREATEPROCEDURE SampleProc()
BEGIN
DECLARE xINT;
SET x = 1;
WHILEx
insert intodictionary (word, mean) values(concat('a',x),concat('a means',x));
SET x = x + 1;
END WHILE;
END
mysql> DELIMITER ;
mysql>call SampleProc();
1.3 SHOW STATUS 观察结果Modify Column 以及Alter Column的区别
首先使用MODIFY COLUMN
mysql> flush status;
Query OK, 0 rows affected (0.00 sec)
mysql> alter table dictionary
->modify column mean varchar(20) NOT null default 'DEFAULT1';
Query OK, 110002 rows affected (3.07 sec)
Records: 110002 Duplicates: 0 Warnings: 0
mysql> SHOW STATUS WHERE Variable_name LIKE'Handler%'
->OR Variable_name LIKE 'Created%';
+----------------------------+--------+
| Variable_name | Value |
+----------------------------+--------+
| Handler_read_rnd_next | 110003 |
| Handler_rollback | 0 |
| Handler_savepoint | 0 |
| Handler_savepoint_rollback | 0 |
| Handler_update | 0 |
| Handler_write | 110002 |
+----------------------------+--------+
在使用ALTER COLUMN
mysql> flush status;
mysql> alter table dictionary
-> alter column mean set default'DEFAULT2';
Query OK, 0 rowsaffected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW STATUSWHERE Variable_name LIKE 'Handler%'
-> OR Variable_name LIKE 'Created%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
|Handler_read_rnd_next | 0 |
|Handler_savepoint_rollback | 0 |
| Handler_update | 0 |
| Handler_write | 0 |
2 修改frm文件
通过修改frm文件的方式来提高修改表结构效率的步骤大概如下
1. 备份相关的数据库文件
2. 创建一张和旧表完全相同的表结构
mysql>create table dictionary_new like dictionary;
3. 执行FLUSH TABLES WITH READ LOCK. 所有的表都被关闭
mysql> alter table dictionary_new
-> modify column mean varchar(30)default 'DEFAULR#';
mysql> flush table with read lock;
5. 把dictionary_new.frm文件重名为dictionary.frm
6. 执行UNLOCK TABLES
mysql> unlock tables;
mysql> insert into dictionary(word) values('Random');
mysql> select * from dictionarywhere word='Random';
从下面的结果可以看出,默认值已经被改掉,且不涉及到内容的改变
+--------+--------+----------+
| id | word | mean |
+--------+--------+----------+
| 110004 |Random | DEFAULR# |
+--------+--------+----------+
7. Drop dictionary_new

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software