search
HomeDatabaseMysql TutorialMySQL优化全攻略--相关数据库命令_MySQL

MySQL优化全攻略--相关数据库命令_MySQL

Jun 01, 2016 pm 02:11 PM
mysqloptimizationComplete strategyOrderdatabaseRelated

MySQL优化


  ▲ SHOW
  
  执行下面这个命令可以了解服务器的运行状态:
  
  mysql >show status;
  
  该命令将显示出一长列状态变量及其对应的值,其中包括:被中止访问的用户数量,被中止的连接数量,尝试连接的次数,并发连接数量最大值,以及其他许多有用的信息。这些信息对于确定系统问题和效率低下的原因是十分有用的。
  
  SHOW命令除了能够显示出MySQL服务器整体状态信息之外,它还能够显示出有关日志文件、指定数据库、表、索引、进程和许可权限表的宝贵信息。请访问http://www.mysql.com/doc/S/H/SHOW.html了解更多信息。
  
  ▲ EXPLAIN
  
  EXPLAIN能够分析SELECT命令的处理过程。这不仅对于决定是否要为表加上索引很有用,而且对于了解MySQL处理复杂连接的过程也很有用。
  
  下面这个例子显示了如何用EXPLAIN提供的信息逐步地优化连接查询。(本例来自MySQL文档,见http://www.mysql.com/doc/E/X/EXPLAIN.html。原文写到这里似乎有点潦草了事,特加上此例。)
  
  假定用EXPLAIN分析的SELECT命令如下所示:
  
  EXPLAIN SELECT tt.TicketNumber, tt.TimeIn,
  tt.ProjectReference, tt.EstimatedShipDate,
  tt.ActualShipDate, tt.ClientID,
  tt.ServiceCodes, tt.RepetitiveID,
  tt.CurrentProcess, tt.CurrentDPPerson,
  tt.RecordVolume, tt.DPPrinted, et.COUNTRY,
  et_1.COUNTRY, do.CUSTNAME
  FROM tt, et, et AS et_1, do
  WHERE tt.SubmitTime IS NULL
  AND tt.ActualPC = et.EMPLOYID
  AND tt.AssignedPC = et_1.EMPLOYID
  AND tt.ClientID = do.CUSTNMBR;
  
  SELECT命令中出现的表定义如下:
  
  ※表定义
  
  表 列 列类型
  tt ActualPC CHAR(10)
  tt AssignedPC CHAR(10)
  tt ClientID CHAR(10)
  et EMPLOYID CHAR(15)
  do CUSTNMBR CHAR(15)
  
  ※索引
  
  表 索引
  tt ActualPC
  tt AssignedPC
  tt ClientID
  et EMPLOYID (主键)
  do CUSTNMBR (主键)
  
  ※tt.ActualPC值分布不均匀
  
  在进行任何优化之前,EXPLAIN对SELECT执行分析的结果如下:
  
  table type possible_keys    key key_len ref rows Extra
  et ALL PRIMARY      NULL NULL NULL 74
  do ALL PRIMARY      NULL NULL NULL 2135
  et_1 ALL PRIMARY      NULL NULL NULL 74
  tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872
  range checked for each record (key map: 35)
  
  每一个表的type都是ALL,它表明MySQL为每一个表进行了完全连接!这个操作是相当耗时的,因为待处理行的数量达到每一个表行数的乘积!即,这里的总处理行数为74 * 2135 * 74 * 3872 = 45,268,558,720。
  
  这里的问题之一在于,如果数据库列的声明不同,MySQL(还)不能有效地运用列的索引。在这个问题上,VARCHAR和CHAR是一样的,除非它们声明的长度不同。由于tt.ActualPC声明为CHAR(10),而et.EMPLOYID声明为CHAR(15),因此这里存在列长度不匹配问题。
  
  为了解决这两个列的长度不匹配问题,用ALTER TABLE命令把ActualPC列从10个字符扩展到15字符,如下所示:
  
  mysql > ALTER TABLE tt MODIFY ActualPC VARCHAR(15);
  
  现在tt.ActualPC和et.EMPLOYID都是VARCHAR(15)了,执行EXPLAIN进行分析得到的结果如下所示:
  
  table type possible_keys key  key_len ref   rows Extra
  tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 where used
  do ALL PRIMARY   NULL NULL NULL  2135
  range checked for each record (key map: 1)
  et_1 ALL PRIMARY   NULL NULL NULL  74
  range checked for each record (key map: 1)
  
  et eq_ref PRIMARY   PRIMARY 15  tt.ActualPC 1
  
  这还算不上完美,但已经好多了(行数的乘积现在少了一个系数74)。现在这个SQL命令执行大概需要数秒钟时间。
  
  为了避免tt.AssignedPC = et_1.EMPLOYID以及tt.ClientID = do.CUSTNMBR比较中的列长度不匹配,我们可以进行如下改动:
  
  mysql > ALTER TABLE tt MODIFY AssignedPC VARCHAR(15),
  MODIFY ClientID VARCHAR(15);
  
  现在EXPLAIN显示的结果如下:
  
  table type possible_keys key  key_len ref   rows  Extra
  et ALL PRIMARY   NULL NULL NULL   74
  tt ref AssignedPC,ClientID,ActualPC ActualPC 15 et.EMPLOYID 52 where used
  et_1 eq_ref PRIMARY   PRIMARY 15  tt.AssignedPC 1
  do eq_ref PRIMARY   PRIMARY 15  tt.ClientID 1
  
  这个结果已经比较令人满意了。
  
  余下的问题在于,默认情况下,MySQL假定tt.ActualPC列的值均匀分布,而事实上tt表的情况并非如此。幸而,我们可以很容易地让MySQL知道这一点:
  
  shell > myisamchk --analyze PATH_TO_MYSQL_DATABASE/tt
  shell > mysqladmin refresh
  
  现在这个连接操作已经非常理想,EXPLAIN分析的结果如下:
  
  table type possible_keys key  key_len ref   rows Extra
  tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 where used
  et eq_ref PRIMARY   PRIMARY 15  tt.ActualPC 1
  et_1 eq_ref PRIMARY   PRIMARY 15  tt.AssignedPC 1
  do eq_ref PRIMARY   PRIMARY 15  tt.ClientID 1
  
  ▲ OPTIMIZE
  
  OPTIMIZE能够恢复和整理磁盘空间以及数据碎片,一旦对包含变长行的表进行了大量的更新或者删除,进行这个操作就非常有必要了。OPTIMIZE当前只能用于MyISAM和BDB表。
  
  结束语:
  
  从编译数据库服务器开始、贯穿整个管理过程,能够改善MySQL性能的因素实在非常多,本文只涉及了其中很小的一部分。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

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.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

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.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

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: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

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: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

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: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

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.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

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.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool