Seven, index optimization analysis

The reason SQL performance degradation

  • Query badly written
  • Failure Index
  • Too many inquiries related
  • Server tuning and setting of each parameter (buffer, the number of threads, etc.)

Common JOIN query

1, SQL execution order

Handwritten order:

The order of execution of real machine:

2 or seven join query

The last two mysql syntax is not supported, but we can come together with other union query results to piece together the final result.

index

1. What is the index?

MySQL is the official definition of the index: the index (Index) to help MySQL efficiently get the data structure of the data.

It can be simply understood as "sorted quickly find data structure."

Addition to the data itself, the database also maintains a data structure to meet specific search algorithm, these data point to data structures in some way, so that you can achieve the advanced search algorithm on the basis of these data structure, this data structure is indexed.

In general the index itself is also great, it can not all be stored in memory, so they are often in the form of index files stored on disk.

2, the index strengths and weaknesses

Advantage

  • Improve data retrieval efficiency and reduce the cost of database IO
  • It reduces the cost of sorting data, reducing the CPU usage

Disadvantaged

  • In fact, the index is also a table that holds the primary key and index fields, and points to record a solid table, so the index column is to take up space
  • Although the index greatly increased query speed, but will also reduce the speed of updating the table, because the update table, MySQL is not only to save the data, but also save about index file is updated each time adding a field index column will adjust because index update information after key changes brought about by

3, the index of classification

  • Single-valued index: the index contains only a single column, a single table may have a plurality of index values
  • The only index: the index column value must be unique, but allow free value
  • Composite index: the index comprises a plurality of columns

4, basic grammar

  • create

    CREATE [UNIQUE] INDEX indexName ON table_name(columnname(length))

    ALTER table_name ADD [UNIQUE] INDEX indexName ON (columnname(length))

    If when CHAR, VARCHAR type, length can be less than the actual length of the field, and if a BLOB TEXT types, must be specified length

  • delete

    DROP INDEX [indexName] ON table_name

  • 查看

    SHOW INDEX FROM table_name

5、哪些情况需要创建索引?

  • 主键自动建立唯一索引
  • 频繁作为查询条件的字段应该创建索引
  • 查询中与其他表关联的字段,外键关系建立索引
  • 频繁更新的字段不合适创建索引
  • Where条件里用不到的字段不创建索引
  • 在高并发下倾向创建组合索引
  • 查询中排序的字段,排序字段若通过索引去访问将大大提高排序速度
  • 查询中统计或者分组的字段

6、哪些情况不需要创建索引?

  • 表记录太少
  • 经常增删改的表
  • 如果某个数据列包含许多重复的内容,为它建立索引就没有太大的实际效果

Guess you like

Origin www.cnblogs.com/lee0527/p/12236130.html