Mysql based index that thing ----



武汉加油!!!

background

What database? The question we all know, used to store data, the amount of life you deposit in the bank, or a household are stored in the household and personal information, such as a school student in information and so on, these in our database are stored inside the data in the database do not generally use some of the DML语句(insert, update, delete) to perform data manipulation. want to see the data inside the database using a select statement to query data.

For data stored in a database and can be simply understood as similar Excel表格, form which each line represents one data A Sheet页to represent a class of data.
一个例子Now we have an excel spreadsheet, stored inside a school's student information, including student number, name , class, grade, and so forth

  • If, if only this table inside the store less data ( 几十条, 或者十几条), now let you 找到关于张三学生的信息, we will start from top to bottom or start browsing each row of data from bottom to top, until you find 张三, it will complete the query data.
  • However, a large amount of data, the storage of thousands of data excel, let you find out Joe Smith, you still need top to bottom, or start looking from the bottom up 张三, this time because the data changed much, you may find a cause Joe Smith, you may want to browse some time to find out Joe Smith.

The above example, is a classic problem of data query, how to solve this problem? By the index to

另一个例子Joe Smith bought a book "How the Steel Was Tempered" read it again later, after only six months suddenly remembered 人最宝贵的东西是生命.生命对人来说只有一次.因此,人的一生应当这样度过:当一个人回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧..but forgotten after the last part, just remember that in a chapter ( 我记得是好像是在整书结尾来着), then by Joe Smithtable of ContentsI found this chapter, which quickly begins this chapter to find the last part of this sentence.

Well, this directory can be understood as a 索引speed main purpose is to speed up queries

index

In the above two life examples described 索引是什么以及索引的功能in our database, the truth is the same,
索引: index is used to quickly find a specific value in a column line, do not use an index, MySQL must be from a record start to read the entire list until you find the relevant line, the larger the table, the more time it takes to query the data, a column in a query if the table has an index, MySQL can quickly get a position to search data file, it will save a large part of the time
索引存储类型: when a column as an index of the data query becomes the index to go first, and then according to the index to find this piece of data in order to further enhance the efficiency of queries so, it introduces some. data structure algorithms to improve efficiencyMySQL中的索引的存储类型有两种:BTREE、HASH。 也就是用树或者Hash值来存储该字段

  • 优点:
    • In theory any field type can be indexed.
    • Significantly improve the speed of query
  • 缺点:
    • Index creation time consuming, and the index also requires maintenance, maintenance workload will increase
  • 何时使用 :
    • For the field often as a query priority index
    • Data change frequently to avoid excessive indexing table
    • A small amount of data tables, indexes do not build as much as possible, because the query because the data are less likely to spend less time than the entire traversing the index time.

Storage Engine

For Mysql first thing to know is: 索引是在存储引擎中实现的,也就是说不同的存储引擎,会使用不同的索引so first come to know about several mysql storage engine.

There is a characteristic of MySQL called "Pluggable Storage Engine Architecture" (replaceable storage engine architecture), which means MySQL database offers a variety of storage engines. Users can choose different storage engines depending on the demand for data tables, users can also write your own storage engines according to their needs.

Storage Engine species
Engine name Explanation
CSV Based CSV file format for storing data (data exchange used in cross-platform)
Archive Once the data is compressed for storage, ideal for storing a large number of independent data as history, but only 插入and 查询operation
Falcon A new storage engine that supports transaction processing
Memory Memory storage engine, with a high insert, update and query efficiency. But proportional to the amount of data and it can take up memory space. Only the data stored in the memory means that data may be lost
MRG_MyISAM(MERGE) Multiple table joins a table to use, useful when ultra-large-scale data storage
MONTHLY MyISAM's predecessor, after MySQL5.0 no longer installed by default
MyISAM 高速引擎,拥有较高的插入,查询速度,但不支持事务
InnoDB 5.5版本后MySQL的默认数据库,支持事务和行级锁定,比MyISAM处理速度稍慢

Listed in the table is supported by several Mysql storage engine, which the latter two are the most used in the production and development program, let's focus on what.

MyISAM engine

This engine can be subdivided into 动态, 静态, 压缩are three:

  • 静态MyISAM: If the length of each data column in the data table are fixed in advance good, the server will automatically select that table type. Because the data table each record space is occupied by the same, so that the table access and update efficiency is very high.

  • 动态MyISAM: If the data appears in the table varchar, xxxtext或xxxBLOBwhen the field, the server will automatically select that table type. With respect to the static MyISAM, such a table relatively small storage space, but due to the varying lengths of each record, so many changes data, the data table may be stored in a discrete memory, leading to decreased efficiency. Meanwhile, the memory may be a lot of debris. Thus, this type of table to be used frequently optimize table 命令或优化工具来进行碎片整理.

  • 压缩MyISAM: Speaking of the above two types of tables can be compressed with myisamchk tool. This type of table further reduce memory consumption, but can not be changed after this table compression. Further, since the data is compressed, so that when the first table row decompressed when read.

  • 优点: It has a high query and write speed, independent of the operating system constraints, not the win and linux

    • Suitable for intensive selection table. MyISAM storage engine 筛选大量数据时非常迅速, inserted intensive table. MyISAM concurrent insertion feature allows simultaneous selection and insert the data.
  • 缺点: It does not support transactions

InnoDB engine

InnoDB table types can be seen as a product update for MyISAM, which provides 事务, 行级锁机制and 外键约束functions, but also support the child and so increase AUTO_INCREMENT column attribute.

However, since it will create its own dedicated buffer pool in the main memory to cache data and indexes, InnoDB than MyISAM tables require more memory and storage.

== Notes, even in the same database, or you can mix a variety of storage engine, if needed to support the transaction, you can choose InnoDB, if the database requires a temporary table for the query, you can select MEMORY storage engine ==

Indexing

In mysql InnoDB MyISAM engine and default to store the index structure B + Tree, where B + tree index and divided into two categories

  • Clustered index: refers to the same sort of index entries and data recording mode to sort the table index, 每张表只能有一个聚集索引clustered index leaf node stores the entire line of data.
    一个例子: Dictionary, we have used it, the dictionary data is regarded as a particular table, then the directory is the dictionary 聚集索引, and the dictionary phonetic directory is arranged to from a through z, and each word in the dictionary in accordance with also be arranged in the header portion az alphabet, which is consistent ordering index entries and data recording mode ranking table.
    真实场景For InnoDB table engine, usually we will set a primary key, and most of the time the primary key is auto-incremented, that at the moment 主键便是一个聚集索引, if we do not explicitly set the primary key of a data table when the table for InnoDB engine and how to handle it?

    • First, if a primary key is defined, then the primary key is a clustered index
    • Secondly, if the definition of the primary key is not displayed, the first one of the table 唯一非空索引would be as an aggregate index
    • Finally, if no primary key, and 唯一索引there there is no suitable, then innodb internally generates a hidden primary key as an aggregate index, the hidden primary key is a six byte column, the value of the column is inserted as data increment.
  • Non-clustered index: the index of non-clustered index order of logical uplink physical disk storage order different, a table can have multiple non-clustered index. Leaf node does not contain all of the data rows. In addition to the leaf nodes contain keys, also stores a pointer to the data diverted to build a clustered index bookmark.

Here we introduce a word, 唯一索引one might read, an index that type in the following upcoming Speaking of, I believe after reading the subsequent length should understand.

Index Type

In order to improve the efficiency of queries, we use the index, but the index in order to respond to different scenarios are divided into the following categories

  • A separate index
    • General index
    • The only index
    • Primary key index
  • Composite index
  • Full-text index
  • Spatial Index
A separate index of ordinary index

首先要明白的是, 单列索引是指, 一个索引只包含一个列, 但是一个表中可以建立多个单列索引
In view of the following general index, the name suggests, it is to a row in a data table as an index, 是Mysql中最基本的索引类型, 没有什么限制并且允许在定义索引的列中插入重复值和空值

Create a way

  • Directly create index
CREATE INDEX index_name ON table(column(length));
  • Modify table structure to create the index mode
ALTER TABLE table_name ADD INDEX index_name ON (column(length));
  • Create a table when creating an index
CREATE TABLE `table` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `column1` char(255) CHARACTER NOT NULL ,
    `column2` text CHARACTER NULL ,
    PRIMARY KEY (`id`),
    INDEX index_name (column1(length))
)
The only single-column index of the index

Similar general index, is different: the index of the column 值必须唯一, but 允许有空值. If a combination of the index, then 列值的组合必须唯一, which is similar to A + B, B + C, C + D of this, a data table can not have two A + B.

Create a way

  • Directly create index
CREATE UNIQUE INDEX indexName ON table(column(length));
  • Modify table structure to create the index mode
ALTER TABLE table_name ADD UNIQUE indexName ON (column(length));
  • Create a table when creating an index
CREATE TABLE `table` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `column1` char(255) CHARACTER NOT NULL ,
    `column2` text CHARACTER NULL ,
    PRIMARY KEY (`id`),
    UNIQUE indexName (column1(length))
)
A separate index of the primary key index

It can be seen as a variant of a unique index, a table can have 一个主键, 不允许有空值. Usually at the same time create a primary key index when construction of the table

Create a way

  • Directly create index
CREATE TABLE `table` (
    `id` int(11) NOT NULL AUTO_INCREMENT ,
    `column1` char(255) CHARACTER NOT NULL ,
    `column2` text CHARACTER NULL ,
    PRIMARY KEY (`id`)
)
Composite index

Index finger on multiple fields created only used in the query 创建索引时的第一个字段, the index will be used. Follow when using the combination index最左前缀集合

Commentary description 最左前缀集合
一个例子a table, we have name, age, addresscreate an index, then the index in accordance with the name/age/addressplacement of the order,
we can use when in use (name, age, address), or (name, age)Or (name, address)you can seenameHe was seen as our most left-prefix.

If the query time use (age, address), or (age, name)such a sequence is not the index data of the query. Query is referred to as an ineffective.

Create a way

ALTER TABLE `table` ADD INDEX name_age_address ((name, age, address); 
Full-text index

The main keywords used to find the text, rather than directly compared with the value of the index, with a bunch of text, such as a keyword by them, you will find rows of the field belongs to, for example 武汉加油, by 武汉, , keywords, etc. can be found to the entire corresponding data.
this indexing is reflected in many non-relational databases, e.g. ES, or MongoDB

pay attentionIn mysql 全文索引只有在MyISAM引擎can use, and only the char、varchar,textcolumns you can create full-text index

Spatial Index

Spatial index is an index of spatial data type of field established spatial data types in MySQL four, GEOMETRY, the POINT, LINESTRING, POLYGON
mysql5.7 and later support, to create when using the SPATIAL keyword and columns involved can not Is empty.

This index, the author of the current production development, not encountered, avoid saying incomplete mislead you, if needy students can refer to some of the following documents
spatial indexes and ST_Geometry
MySQL5.7 version of the spatial data reference documentation
MySQL support spatial data formats
ST_Within

to sum up

  • Why use an index?
    • Accelerate query efficiency
  • Index categories have?
    • A separate index
      • General index
      • The only index
      • Primary key index
    • Composite index
    • Full-text index
    • Spatial Index

Speaking of 索引, have to mention 视图, that view is how it is, the venue "view those things ---- based Mysql"

发布了106 篇原创文章 · 获赞 10 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_32060101/article/details/104194468