search
HomeDatabaseMysql TutorialDetailed introduction to MySQL storage engine

Detailed introduction to MySQL storage engine

Jul 20, 2017 pm 09:02 PM
mysqlstorageengine

 What is a storage engine?

A relational database table is a data structure used to store and organize information. A table can be understood as a table composed of rows and columns, similar to the form of an Excel spreadsheet. Some tables are simple, some are complex, some tables are not used to store any long-term data at all, and some tables are very fast to read, but very poor when inserting data; in the actual development process, we may need Various tables, different tables, mean that different types of data are stored, and there will be differences in data processing. For MySQL, it provides many types of storage engines. We can choose different storage engines according to our data processing needs, so as to maximize the use of MySQL's powerful functions. This blog post will summarize and analyze the characteristics of each engine and its applicable situations, and will not get entangled in deeper things. My learning method is to first learn to use it, know how to use it, and then find out how to use it. The following is a brief introduction to the storage engines supported by MySQL.

Detailed introduction to MySQL storage engine

MySQL 5.5 and later uses the InnoDB storage engine by default. InnoDB and BDB provide transaction-safe tables, and other storage engines are non-transaction-safe tables.

To modify the default engine, you can modify the default-storage-engine in the configuration file. You can use: showvariableslike'default_storage_engine'; to view the current database to the default engine. Commands: showengines and showvariableslike'have%' can list the engines supported by the current database. Records in which Value is displayed as disabled indicate that the database supports this engine and is disabled when the database is started. After MySQL5.1, there is an ENGINES table in the INFORMATION_SCHEMA database. The information it provides is exactly the same as the showengines; statement. You can use the following statement to query which storage engines support transaction processing: selectenginefrominformation_chema.engineswheretransactions='yes';

You can use the engine keyword to specify the engine used when creating or modifying the database.

Main storage engines: MyISAM, InnoDB, MEMORY and MERGE Introduction:

When creating a table, specify the engine to be used through engine=... or type=.... showtablestatusfromDBname to view the specified table to the engine.

 (1)MyISAM

It does not support transactions or foreign keys, especially applications with fast access speed, no requirements for transaction integrity, or applications based on SELECT and INSERT. Tables can be created using this engine.

Each MyISAM is stored as 3 files on the disk. The file names and table names are the same, but the extensions are:

.frm (storage table definition)

MYD (MYData, storage data)

MYI (MYIndex, storage index)

Data files and index files can be placed in different directories to evenly distribute IO and obtain faster speeds. To specify the path of the data file and index file, you need to specify it through the DATADIRECTORY and INDEXDIRECTORY statements when creating the table. The file path needs to use an absolute path.

Each MyISAM table has a flag. The server or the myisamchk program will set this flag when checking the MyISAM data table. The MyISAM table also has a flag to indicate whether the data table was closed normally after the last use. If the server is down or crashed, this flag can be used to determine whether the data table needs to be checked and repaired. If you want this check to happen automatically, you can use the --myisam-recover phenomenon when starting the server. This will cause the server to automatically check the table's flags every time it opens a MyISAM data table and make necessary repairs. MyISAM type tables may be damaged. You can use the CHECKTABLE statement to check the health of the MyISAM table, and use the REPAIRTABLE statement to repair a damaged MyISAM table.

MyISAM tables also support 3 different storage formats:

Static (fixed length) table

Dynamic table

Compressed table

 Static table is the default storage format. The fields in static tables are all non-variable length fields, so each record has a fixed length. The advantages of this storage method are that it is stored very quickly, is easy to cache, and is easy to recover from failures. The disadvantage is that it usually takes up more space than a dynamic table. . Static tables will fill in spaces according to the width definition of column definitions when data is stored, but these spaces will not be obtained when accessed. These spaces have been removed before being returned to the application. At the same time, please note: In some cases, it may be necessary to return spaces after the field, and when using this format, subsequent spaces will be automatically processed.

Dynamic tables contain variable-length fields and records are not of fixed length. The advantage of such storage is that it takes up less space. However, frequent updates and deletions of records will cause fragmentation. You need to execute the OPTIMIZETABLE statement or the myisamchk-r command regularly. Improves performance and makes recovery from failures relatively difficult.

The compressed table is created by the myisamchk tool and occupies a very small space. Because each record is compressed individually, there is only a very small access overhead.

 (2)InnoDB

InnoDB is a robust transactional storage engine. This storage engine has been used by many Internet companies and provides a powerful tool for users to operate very large data storage. solution. MySQL version 5.6.13 is installed on my computer, and InnoDB is the default storage engine. InnoDB also introduces row-level locking and foreign key constraints. In the following situations, using InnoDB is the most ideal choice:

 1. Update intensive tables. The InnoDB storage engine is particularly suitable for handling multiple concurrent update requests.

 2. Affairs. The InnoDB storage engine is a standard MySQL storage engine that supports transactions.

 3. Automatic disaster recovery. Unlike other storage engines, InnoDB tables can automatically recover from disasters.

 4. Foreign key constraints. The only storage engine that supports foreign keys in MySQL is InnoDB.

 5. Support automatically adding column AUTO_INCREMENT attribute.

The InnoDB storage engine provides transaction security with commit, rollback, and crash recovery capabilities. However, compared with MyISAM's storage engine, InnoDB's write processing efficiency is less efficient and takes up more disk space to retain data and indexes.

 1) Automatic growth column:

The automatic growth column of the InnoDB table can be inserted manually, but if the inserted value is empty or 0, the actual value inserted is the value after automatic growth. The starting value of the automatic growth value can be forcibly set through the "ALTERTABLE...AUTO_INCREMENT=n;" statement. The default value is 1, but the forced default value is stored in memory and will be lost after the database is restarted. You can use LAST_INSERT_ID() to query the value used by the current thread to insert the record last time. If multiple records are inserted at one time, the auto-increment value used by the first record is returned.

For InnoDB tables, the auto-growing column must be an index. If it is a composite index, it must also be the first column of the composite index. However, for MyISAM tables, the automatic growth column can be other columns of the composite index. In this way, after inserting a record, the automatic growth column is incremented after sorting the previous columns of the composite index. of.

2) Foreign key constraints:

The only storage engine that supports foreign keys in MySQL is InnoDB. When creating a foreign key, the parent table must have a corresponding index, and the child table must have a corresponding index when creating a foreign key. Corresponding indexes will also be automatically created.

When creating an index, you can specify the corresponding operations on the child table when deleting or updating the parent table, including restrict, cascade, setnull and noaction. Among them, restrict and noaction are the same, which means that the parent table cannot be updated when the child table is related; casecade means that when the parent table is updated or deleted, the records corresponding to the child table are updated or deleted; setnull means that the parent table is updated or deleted. When deleting, the corresponding field of the subtable is setnull.

When a table is referenced by a foreign key created by another table, the corresponding index or primary key of the table is prohibited from being deleted.

You can use setforeign_key_checks=0; to temporarily turn off foreign key constraints, and setforeign_key_checks=1; to turn on constraints.

(二)InnoDB

 (3)MEMORY

Memory uses the contents stored in memory to create tables. Each MEMORY table actually corresponds to a disk file, the format is .frm. MEMORY type table access is very fast because the data is stored in memory and HASH indexes are used by default. However, once the server is shut down, the data in the table will be lost, but the table will continue to exist.

By default, memory data tables use hash indexes. Using this index to perform "equality comparison" is very fast, but "range comparison" is much slower. Therefore, the hash index value is suitable for use in the "=" and "" operators, but is not suitable for use in the "" operators, and is also not suitable for use in the orderby clause. inside. If you really want to use the "" or betwen operators, you can use a btree index to speed things up.

The data rows stored in the MEMORY data table use a constant-length format, thus speeding up processing. This means that variable-length data types such as BLOB and TEXT cannot be used. VARCHAR is a variable-length type, but because it is treated internally by MySQL as a fixed-length CHAR type, it can be used.

Createtabletab_memoryengine=memoryselectid,name,age,addrfrommanorderbyid;

Use USINGHASH/BTREE to specify the index.

 createindexmem_hashusinghashontab_memory(city_id);

Use the --init-file option when starting the MySQL service and put statements like insertinto...select or loaddatainfile into this file. Tables can be loaded from a durable data source when the service starts.

The server needs enough memory to maintain the MEMORY table that is used at the same time. When the MEMORY table is no longer used, to release the memory occupied by the MEMORY table, you should execute DELETEFROM or truncatetable or delete the entire table.

The amount of data placed in each MEMORY table is constrained by the max_heap_table_size system variable. The initial value of this system variable is 16M. At the same time, when creating a MEMORY table, you can use the MAX_ROWS clause to specify the maximum number of rows in the table. .

The starting point for using the MySQL Memory storage engine is speed. To get the fastest response time, the logical storage medium used is system memory. Although storing table data in memory does provide high performance, when the mysqld daemon crashes, all Memory data is lost. With the speed gained comes some drawbacks. It requires that the data stored in the Memory data table use a constant-length format, which means that variable-length data types such as BLOB and TEXT cannot be used. VARCHAR is a variable-length type, but because it is MySQL internally treats it as a CHAR type with a fixed length, so it can be used.

 (4)MERGE

The merge storage engine is a combination of a set of MyISAM tables. The structures of these MyISAM tables must be exactly the same. There is no data in the MERGE table. You can query the MERGE type table. , update, and delete operations. These operations are actually operations on the internal MyISAM table. For the insert operation into the MERGE table, the inserted table is defined according to the INSERT_METHOD clause. It can have three different values. The first and last values ​​make the insert operation act on the first or last table accordingly. Define this clause or set it to NO, indicating that the MERGE table cannot be inserted. You can perform a drop operation on the MERGE table. This operation only deletes the definition of the MERGE table and has no impact on the internal tables. MERGE retains two files starting with the MERGE table name on the disk: the .frm file stores the definition of the table; the .MRG file contains information about the combined table, including which tables the MERGE table is composed of, and the basis for inserting data. The MERGE table can be modified by modifying the .MRG file, but it must be refreshed through flushtable after modification.

createtableman_all(idint,namevarchar(20))engine=mergeunion=(man1,man2)insert_methos=last;

(三)MEMORY   

The above is the detailed content of Detailed introduction to MySQL storage engine. For more information, please follow other related articles on the PHP Chinese website!

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
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

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

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment