search
HomeDatabaseMysql Tutorial 高性能的MySQL(5)索引策略一压缩,冗余,重复,索引和锁

一、压缩索引MyISAM使用前缀压缩来减少索引的大小,默认只压缩字符串,但是通过设置也可以对整数做压缩。压缩可以使用更少的空间,代价是某些操作可能更慢。特别

一、压缩索引

MyISAM使用前缀压缩来减少索引的大小,默认只压缩字符串,但是通过设置也可以对整数做压缩。

压缩可以使用更少的空间,代价是某些操作可能更慢。特别是倒序的查询,测试表明,对于CPU密集型的应用,查询会很慢,特别是倒序。对于I/O密集型应用,查询可能会不错。

可以在CREATE TABLE的语句中指定PACK_KEYS参数来指定索引压缩方式。


二、冗余和重复索引

重复索引:指在相同的列上按照相同的顺序创建的相同类型的索引,要尽量避免重复索引,除非在同一列上创建不同类型的索引来满足不同的查询需求。比方说 key(col) 和 fulltext key(col)。

冗余索引:如果创建了索引(A,B),再创建索引(A)就是冗余索引。因为索引(A,B)也可以当作(A)来使用(只针对B-Tree)。但是如果再创建索引(B,A)或者(B),则不是冗余索引。或者类型不同,比方说哈希,全文索引等。

冗余索引通常发生在添加索引的时候,大多数情况下都不需要冗余索引,而是尽量扩展已有的索引,除非扩展已有的索引会导致索引很大,,从而影响其他使用索引的性能。

例如:在一个整数列的索引上扩展一个很长的varchar列的索引,性能可能就会急剧下降。但是增加一个新的索引,就会对增删改操作影响很大,所以要平衡使用。


如何找到这写索引,以便删除,可以访问INFORMATION_SCHEMA,或者一些现有的工具来定位。

有一个值得注意的地方:

对于InnoDB因为二级索引包换了主键,所以列(A)上的索引就相当与(A,ID),所以类似

where A=5 order by id 这样的查询,这个索引会很有用。但是扩展为索引(A,B)

之后,则实际变成了(A,B,ID),则order by就无法用到索引排序了。


三、索引和锁

索引可以让查询锁定更少的行,因为索引可以让查询不访问那些不需要的行,那么就会锁定更少的行。这有2点好处:

1、减少锁定行带来的额外的开销。

2、锁定超过需要的行会增加锁争用和减少并发性。


InnoDB只有在访问行的时候才会对其加锁,而索引能减少InnoDB访问的行数,从而减少锁的数量。但这只有当InnoDB在存储引擎层能够过滤掉所有不需要的行时才有效。如果索引无法过滤掉无效的行,那么在InnoDB检索到数据返回给服务器层以后,MySQL服务器才能应用WHERE子句进行过滤。这时候已经无法避免锁定行了,InnoDB已经锁定了所有返回的数据行。

举例说明:表结构

CREATE TABLE `emp3` ( `id` int(11) NOT NULL DEFAULT '0', `name` varchar(100) NOT NULL, `job` varchar(100) NOT NULL, `num1` int(10) DEFAULT NULL, `num2` int(10) DEFAULT NULL, `num3` int(10) DEFAULT NULL, `job_num` int(10) DEFAULT NULL, `d` date DEFAULT NULL, PRIMARY KEY (`id`), KEY `job_num` (`job_num`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

数据如下:

151658496.png

在一个终端执行如下的操作:

151920121.png

虽然只返回了10002-10004之间的行,但是实际上10001-10004都被锁定了

152151828.png

也就是说,底层存储引擎的操作是从索引开头开始获取满足id

我们来证明第一行确实是被锁定了,保持这个终端链接不关闭,然后我们打开另一个终端。

171221780.png

这个查询会挂起,知道第一个事务释放了第一行的锁。

按照这个例子,即使使用了索引,InnoDB也可能锁住一些不需要的数据。如果不能使用索引查找和锁定行的话,结果会更糟。MySQL会全表扫描并锁住所有的行,而不管是不是需要。



本文出自 “phper-每天一点点~” 博客,请务必保留此出处

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
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.