Mysql database performance optimization 2 _ MySQL

Source: Internet
Author: User
Tags dname
This article mainly introduces Mysql database performance optimization 2. if you need it, you can refer to the previous article to introduce mysql database performance optimization 1, today, I will continue my previous article to introduce you to database performance optimization. The specific content is as follows:

Create an appropriate index

To improve database performance, indexing is the best and inexpensive. There is no need to add memory, no need to change the program, no need to tune the SQL, as long as the correct 'create index' is executed, the query speed may be improved by Times, which is really tempting. However, there is no free lunch in the world, and the query speed is improved at the cost of the insert, update, and delete speeds. These write operations increase a lot of I/O.

Is creating an index able to solve all the problems? What if no index is created on ename?

Select * from emp where ename = 'R & D authority ';

--- Test case command (preferably select * from emp e, dept d where e. empno = 123451)

* Add a primary key

ALTER TABLE emp ADD PRIMARY KEY(empno);

* Deleting a primary key

alter table emp drop primary key;

Principles of indexing

Why is no index slow?

Why is indexing faster?

Index cost

1. disk usage

2. impact on efficiency of dml (update delete insert) statements

Btree retrieval, algorithm complexity: log2N times

Which columns are suitable for indexing?

1. index should be created frequently as a query condition field

select * from emp where empno = 1;

2. fields with poor uniqueness are not suitable for independent index creation, even if they are frequently used as query conditions

Select * from emp where sex = 'male'

3. frequent updates to fields are not suitable for index creation.

select * from emp where logincount = 1

4. fields that do not appear in the WHERE clause should not be indexed

Index type

• Primary key index, which is automatically used as the Primary Index (type Primary)

• UNIQUE index (UNIQUE)

• General INDEX)

• Full-text index (FULLTEXT) [for MyISAM] -- "sphsf-+ Chinese word segmentation coreseek [Chinese version of sphsf-]

• Comprehensive use => compound index

Differences between the four indexes of mysql

LPRIMARY index = automatically created on the primary key

LUNIQUE index => a UNiQUE index can be created only when the field content is Unique)

LINDEX index => is a common index

LFULLTEXT => this parameter is only supported by the MYISAM storage engine. it is used for full-text indexing. it is used in many content systems and on many websites in Full English (with independent English words ). chinese data is not commonly used and is of little significance. domestic full-text indexes are usually completed using sphinx. full-text indexes can only be created in the char varchar text field.

Full-text index case

1. create a table

create table news(id int , title varchar(32),con varchar(1024)) engine=MyISAM;

2. create a full-text index

create fulltext index ful_inx on news (con);

3. Insert data

Note that the common English fulltext does not match, and the inserted statement is correct.

'but it often happens that they are not above supporting themselves by dishonest means.which should be more disreputable.Cultivate poverty like a garden herb'

4. check the matching degree.

mysql> select match(con) against('poverty') from news;+-------------------------------+| match(con) against('poverty') |+-------------------------------+| 0 || 0 || 0 || 0.9853024482727051 |+------------------------------+

0 indicates that no match is found, or your word is a stopword, so no index will be created.

You cannot use the like statement to use full-text indexes.

Composite Index

Create index name on table name (Column 1, column 2 );

Use of indexes

Create an index

Create [UNIQUE | FULLTEXT] index index_name on tbl_name (col_name [(length)] [ASC | DESC],...); Alter table table_name add index [index_name] (index_col_name,...) ADD a primary key (INDEX) alter table table name add primary key (column name,...); join a PRIMARY KEY

Delete index

Drop index index_name ON tbl_name; alter table table_name drop index index_name; delete a primary key (INDEX): alter table t_ B drop primary key;

Query indexes (all available)

show index(es) from table_name;show keys from table_name;desc table_Name;

Modify the index. we usually delete the index first and recreate it.

The most important condition for an index to be used for a query is that the index must be used in the query condition.

Indexes may be used in the following situations:

1. for the created multi-column index, the index is generally used as long as the leftmost column is used in the query condition.

2. for like queries, if '% aaa' is used, indexes are not used, and 'AAA %' is used.

The following tables do not use indexes:

1. if there is or in the condition, it will not be used even if there is a condition with an index.

2. if multiple-column indexes are not the first part, they are not used.

3. the like query starts with %.

4. if the column type is a string, you must quote the data using quotation marks in the condition. Otherwise, no index is used. (When adding, the string must be '')

5. if mysql estimates that full table scan is faster than indexing, no index is used.

Test case (demonstration on the preceding dept table .)

Create table dept (deptno mediumint unsigned not null default 0, dname VARCHAR (20) not null default "", loc VARCHAR (13) not null default "") ENGINE = MyISAM default charset = utf8; -- put the data, which should have been added before. if not, add it again -- start the test.

Add a primary key index

alter table dept add primary key (deptno)

-- Test statement

explain select * from dept where deptno=1;

The result is:

mysql> explain select * from dept where deptno=1;*************************** 1. row ***************************id: 1select_type: SIMPLEtable: depttype: constpossible_keys: PRIMARYkey: PRIMARYkey_len: 3ref: constrows: 1Extra:1 row in set (0.00 sec)

-- Create multi-column indexes

alter table dept add index myind (dname,loc);

-- It is proved that the index is generally used as long as the leftmost column is used for the created multi-column index.

Explain select * from dept where dname = 'R & D department '; the index myindexplain select * from dept where loc = 'msbdpmrx' is used. The index myind is not used.


-- For queries using like

Explain select * from dept where dname like '% R & D department'; the index myindexplain select * from dept where dname like 'R & D department % 'is not displayed. The index myind is used.

-- If there is or in the condition, it will not be used even if the condition has an index.

-- For demonstration, we delete the composite index and then add the index only to the dname.

Alter table dept drop index myindalter table dept add index myind (dname) explain select * from dept where dname = 'R & D department 'or loc = 'aa'; -- the dname column is not used.

-- If the column type is a string, you must quote the data in quotation marks in the condition. Otherwise, no index is used.

Select * from dept from dname = 1234; // The index will not be used. select * from dept from dname = '000000'; // The index will be used.

View Index usage

show status like 'Handler_read%';

Note:

Handler_read_key: the higher the value, the better. the higher the value indicates the number of times the index is queried.

Handler_read_rnd_next: a higher value indicates inefficient query.

* At this time, we will see that handler_read_rnd_next has a high value. why? this is because we performed multiple queries when we didn't add an index before.

Common SQL optimization

About Data insertion in large batches (MySql administrator)

For MyISAM:

Alter table table_name disable keys; loading data // insert statement; alter table table_name enable keys;

For Innodb:

1. sort the data to be imported by primary key

2, set unique_checks = 0, disable the uniqueness check.

3. set autocommit = 0. disable automatic submission.

Optimize group by statements

By default, MySQL sorts all group by col1 and col2. This is similar to specifying order by col1 and col2 in a query. If the query contains group by but you want to avoid consumption of the sorting result, you can use order

Sorting prohibited by null

In some cases, you can use a connection to replace subqueries.

Because join is used, MySQL does not need to create a temporary table in memory. (Explanation)

If you want to use indexes in query statements containing or, indexes must be used for each condition column between or. if there is no index, you should consider adding indexes (related to the environment)

Select * from table name where condition 1 = ''or condition 2 = 'TT' explaine select * from dept group by dname; => extra is displayed: using filesort description will sort explain select * from dept group by dname order by null => In this case, extra: using filesort is not displayed.

* ** In some cases, you can use a connection to replace subqueries. Because join is used, MySQL does not need to create a temporary table in memory.

explain select * from emp , dept where emp.deptno=dept.deptno;


The problem can be explained after comparison with the following !!

explain select * from emp left join dept on emp.deptno=dept.deptno;


Select an appropriate storage engine

MyISAM: the default MySQL storage engine. If the application is dominated by Read and insert operations, there are only a few update and delete operations, and the transaction integrity requirements are not very high. The advantage is that the access speed is fast.

InnoDB: provides transaction security with commit, rollback, and crash recovery capabilities. However, compared with MyISAM, the write processing efficiency is less efficient and will occupy more disk space.

Memory: The data is in Memory, and data is lost when the service is restarted.

MyISAM: when data is inserted, it is placed at the end by default. after data is deleted, the space is not recycled. (transactions and foreign keys are not supported)

InnoDB supports transactions and foreign keys

According to our programmers, the common storage engines are myisam, innodb, memory, and heap tables.

If you choose small principles:

1. if you are pursuing speed and do not care whether the data is always saved or not, select memory to store the user's online status.

2. if the data in the table needs to be permanently saved, the application focuses on read operations and insert operations. there are only a few update and delete operations, and the transaction integrity requirements are not high. Choose MyISAM

3. if you need to persistently store data and provide transaction security with commit, rollback, and crash recovery capabilities, select Innodb

Select an appropriate data type

In applications with high precision requirements, we recommend that you use the number of points to store values to ensure the accuracy of the results. Do not use float for deciaml

For databases whose storage engine is MyISAM, if you often delete and modify records, you must regularly execute the optimize table table_name; function to fragment tables.

The date type should be selected based on actual needs to meet the minimum storage type of the application

Create table bbs (id int, con varchar (1024), pub_time int); date ('ymmd', time-3*24*60*60); 2038-1-19

Case Study of using floating point number and fixed point number

Create table temp1 (t1 float (1000000.32), t2 decimal (1000000.31); insert into temp1 values (,); it is found that t1 is, so there is a problem.


Demo of optimize table name

Create table temp2 (id int) engine = MyISAM; insert into temp2 values (1); insert into temp2 values (2); insert into temp2 values (3 ); insert into temp2 select * from temp2; -- Copy delete from temp2 where id = 1; the data file for this table is not small

Regularly execute optimize table temp2 to find the table size change and complete the fragment.

& For InnoDB, its data will be stored in the data/ibdata1 directory, and there will be only one *. frm table structure file in data/database.

The above is Mysql database performance optimization 2 _ MySQL content. For more information, please follow the PHP Chinese network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.