Mysql uses crc32 fields to create indexes to improve query efficiency

Source: Internet
Author: User
Tags crc32

I have written such an article before, and I will try again.

It is not efficient to create an index for a string field. However, you must check this field frequently to create an index? For example, if the field name is of the sys_trans_id string type, you can create a field sys_trans_id_src32 to store the crc32 value and create an index for the field.

Crc32 is an integer. In MySQL, it is highly efficient to create an index for an integer field. Although crc32 cannot ensure uniqueness, it does not affect the index. The same probability is extremely small, the key is that the query range can be greatly reduced. You can create an index for the sys_trans_id_src32 field, and the crc32 field can be used for the query.


The SQL statement is as follows. For example, if you want to query sys_trans_id and include sys_trans_id_src32 as the index:


EXPLAIN SELECT
 *
FROM
'JS _ checking_third_detail'
WHERE
('Biz _ date' = '20170101 ')
AND ('Diff _ type' IN ('2', '3 '))
AND (
'Sys _ trans_id_src32 '= '201312'
)
AND (
'Sys _ trans_id '= '20140901'
)
AND ('trans _ type' = '1 ')
AND ('pay _ type' = '1 ')
AND ('account _ id' = '1 ')
ORDER
Diff_type DESC,
Biz_date DESC,
Id DESC
LIMIT 0,
50

In this way, the crc32 field is used to check the index usage:

Assume that the crc32 query is not included:

The difference in efficiency is still quite big, and the more data, the more obvious.

The crc32 function of PHP may have a negative value. The correction method is as follows:


/**
* @ Desc CRC32: corrected the negative values in php x86 mode.
* @ Param $ str
* @ Return string
*/
Function jp_crc32 ($ str ){
Return sprintf ("% u", crc32 ($ str ));
}
When storing data, you can also calculate the crc32 value and save it to the database. During the query, you can also calculate the crc32 value of the field to be queried.

Related Article

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.