高性能MySql达尔文主义(五):提速Alter Table
高性能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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting
