Home Database Mysql Tutorial Share Mysql optimization ideas

Share Mysql optimization ideas

Apr 23, 2020 pm 01:37 PM
mysql

1. Overall optimization idea

First build a script to observe the number of queries, number of connections and other data, determine the environmental reasons and internal SQL execution reasons, and then perform specific processing according to the specific reasons.

Recommended: "mysql video tutorial"

2. Build script observation status

mysqladmin -uroot -p  ext \G
Copy after login

This command can obtain information such as the current number of queries, poll regularly and redirect the results to text, and then process them into charts.

3. Solutions

1. If queries appear regularly and slowly, consider the cache avalanche problem.

For this problem, we only need to deal with the cache expiration time so that it does not expire at similar times at the same time. The expiration time should be as discrete as possible, or concentrated until midnight.

2. If the non-regular query is slow, consider the design is not optimized

Processing method:

a: Enable profiling to record query operations and obtain statement execution details

show variables like '%profiling%';
set profiling=on;
select count(*) from user; 
show profiles;
show profile for query 1;
>>>
+--------------------------------+----------+
| Status                         | Duration |
+--------------------------------+----------+
| starting                       | 0.000060 |
| Executing hook on transaction  | 0.000004 |
| starting                       | 0.000049 |
| checking permissions           | 0.000007 |
| Opening tables                 | 0.000192 |
| init                           | 0.000006 |
| System lock                    | 0.000009 |
| optimizing                     | 0.000005 |
| statistics                     | 0.000014 |
| preparing                      | 0.000017 |
| executing                      | 0.001111 |
| end                            | 0.000006 |
| query end                      | 0.000003 |
| waiting for handler commit     | 0.000015 |
| closing tables                 | 0.000011 |
| freeing items                  | 0.000085 |
| cleaning up                    | 0.000008 |
+--------------------------------+----------+
Copy after login

b: Use explain to view statement execution, index usage, scan range, etc.

mysql> explain select count(*) from goods \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: goods
   partitions: NULL
         type: index   
possible_keys: NULL
          key: gid
      key_len: 5
          ref: NULL
         rows: 3
     filtered: 100.00
        Extra: Using index
Copy after login

c: Related optimization techniques

Table optimization and column type selection

Column selection principles:

1: Field type priority integer> date, time > char,varchar > blob

Reason: Integer type, time operation is fast and saves space

char/varchar needs to consider the conversion of the character set and the proofreading set during sorting, and is slow

blob cannot use the memory temporary table

2: Just use enough, don’t be generous (such as smallint, varchar(N))

Reason: Large fields waste memory and affect speed

Use varchar(10), varchar( 300) stores the same content, but when querying tables, varchar(300) takes more memory

3: Try to avoid using NULL

Reason: NULL is not conducive to indexing, so use Special bytes to mark.

The space occupied on the disk is actually larger

Index optimization strategy

1. Index type

1.1 B-tree index (sorted fast search structure)

Note: In Myisam, innodb, the B-tree index is used by default

1.2 hash index

In the memory table, the default is hash index, and the theoretical query time review degree of hash is O(1)

Question: Since hash index is so efficient, why not use it?

The result of a.hash function calculation is random. If the data is placed on the disk, taking the primary key as id as an example, then as the id grows, the row corresponding to the id is randomly placed on the disk. .

b. Unable to optimize range queries

c. Unable to use prefix index, for example, in b-tree, the value of the field column is "helloworld", and the index query xx=hello/xx =helloworld can use the index (left prefix index), but the hash index cannot do it, because hash(hello) and hash(helloworld) are not related.

d. Sorting cannot be optimized either

e. Rows must be returned, the data location must be obtained through the index, and the data must be returned to the table.

2.b-tree Common misunderstandings about indexes

2.1 Add indexes to columns commonly used in where conditions

Example: where cat_id=3 and price>100; //Query the third column, more than 100 yuan The product

is incorrect: both cat_id and price are indexed. In fact, only one index can be used, they are all independent indexes.

2.2 After creating an index on multiple columns, the index will work no matter which column is queried

2.2 Creating an index on multiple columns After indexing, no matter which column is queried, the index will play a role.

Correct answer: For a multi-column index to work, the index needs to meet the left prefix requirement (layered index)

With index(a, b, c) For example:

语句 索引是否发挥作用
where a=3 是
where a=3 and b=5 是
where a=3 and b=5 and c=4 是
where b=3 or where c=4 否
where a=3 and c=4 a列能发挥索引作用,c列不能
where a=3 and b>10 and c=7 a,b能发挥索引作用,c列不能
Copy after login

High performance index strategy

1. For innodb, because there are data files under the node, the split of the node will It becomes slower. For the primary key of innodb, try to use integer type, and it is an increasing integer type.

2. The length of the index directly affects the size of the index file, affects the speed of additions, deletions and modifications, and indirectly affects the query speed (taking up more memory).

3. For the values ​​in the column, intercept parts from left to right to build an index.

a. The shorter the truncation, the higher the degree of repetition, the smaller the distinction, and the worse the indexing effect

b. The longer the truncation, although the discrimination is improved, the index file becomes larger Affects speed

So try to find a balance point in length to maximize performance. Common method: intercept different lengths to test index distinction

Discrimination test:

select count(distinct left(word, 1)) / count(*) from table;
Copy after login

After the test is completed, you can create an index based on the optimal length obtained from the test

alter table table_name add index word(word(4));
Copy after login

Ideal index

1. Frequent queries

2. Discrimination High

3.Small length

4.Try to cover common query fields

The above is the detailed content of Share Mysql optimization ideas. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

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: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

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.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

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.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

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

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles