MySQL’s leftmost matching principle

        The leftmost matching principle of MySQL index: When using a composite index to query, the prefix of the index must be used, otherwise the index will not work. Specifically, if you have a composite index consisting of (a,b,c), you must first filter with a when querying, and then you can filter with b or c, even if b or c are also part of the index.

        The actual meaning of this principle is: when our query conditions contain multiple fields, if a multi-column composite index is established, MySQL will only use the leftmost column in the index as the index key to locate the first matching rows, and then match the remaining conditions one by one. Therefore, if the WHERE clause is not defined in the order of index creation, MySQL will not be able to utilize multi-column indexes and will need to perform a full table scan, which will have a great impact on performance.

For example, let's say we have the following table structure:

CREATE TABLE student (
    id INT NOT NULL PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    gender ENUM('male', 'female') NOT NULL,
    age INT NOT NULL,
    score FLOAT NOT NULL,
    INDEX idx_name_gender_age(name, gender, age)
);

        This table has a composite index idx_name_gender_age, which contains three columns: name, gender and age. If we want to query the information of all female students who are younger than 20 years old, the correct query statement should be like this:

SELECT *
FROM student
WHERE gender = 'female' AND age < 20;

        When MySQL uses the leftmost principle, you will find that you can directly use the first two columns gender and age in the index to filter, so you will use the index to query. If we change the order of conditions and filter based on age first and then gender, we will lose the effect of the index and cause MySQL to scan the entire table.

        Therefore, when building a composite index, you need to pay attention to the order of index columns, and try to put frequently filtered columns first.

Guess you like

Origin blog.csdn.net/weixin_52060913/article/details/130615245