The most left-prefix principles mysql index

Reference 1
Reference 2
best left-prefix rule: take the lead in Big Brother can not die, the middle brother can not be broken
index rules - the best left-prefix rule

Best left-prefix rule learning and demonstration Demo

1 Prepare data

Table 1.1 build
copy the code

DROP TABLE IF EXISTS staff;
CREATE TABLE IF NOT EXISTS staff (
id INT PRIMARY KEY auto_increment,
name VARCHAR(50),
age INT,
pos VARCHAR(50) COMMENT '职位',
salary DECIMAL(10,2)
);

Copy the code

Insert data 1.2

INSERT INTO staff(name, age, pos, salary) VALUES('Alice', 22, 'HR', 5000);
INSERT INTO staff(name, age, pos, salary) VALUES('Bob', 22, 'RD', 10000);
INSERT INTO staff(name, age, pos, salary) VALUES('David', 22, 'Sale', 120000);

2 Test & Explain analysis

2.1 Creating an index

CREATE INDEX idx_nameAgePos ON staff(name, age, pos);

Created based on name, age, pos three fields Index

2.2 Index Test

Case # 1: only to queries based on the name field

EXPLAIN SELECT * FROM staff WHERE name = 'Alice';

result:

type=ref
key=索引
ref=const
ken_len=53

Case # 2: Only query based on name & age field

EXPLAIN SELECT * FROM staff WHERE name = 'Alice' AND age = 22;

Results: Case # 1 and almost, but:

key_len=58
ref=const, const

Case # 3: According name & age & pos to inquiry

EXPLAIN SELECT * FROM staff WHERE name = 'Alice' AND age = 22 AND pos = 'HR';

Results: The index is still in force, at the same time, key_len & ref than Case # 2 results in richer

Case # 4: according to age & pos to inquiry

EXPLAIN SELECT * FROM staff WHERE age = 22 AND pos = 'HR';

Result: no index, a full table scan

Case # 5: According to query the name & pos

EXPLAIN SELECT * FROM staff where name = 'Alice' AND pos = 'HR';

Results: Case # 1 and the same (no access to the index field described pos)

3 Overall analysis

Case1,2,3 are used on the index, using the index and length sequentially increases (key_len = 53,58,111 and ref = 1 th const, 2 th const, 3 th const), the best left-prefix rule;

Case4 not lead brother (Moskva), then, a full table scan;

Case5 field uses only the name of the index, middle brother (intermediate compartment) Age off, then, the latter brother (cabin) linked to the POS;

4 Summary

Best left-prefix rule: take the lead in Big Brother can not die, the middle brother can not be broken

Guess you like

Origin www.cnblogs.com/djwhome/p/12535827.html