Develop

mysql index hint

작은이야기 2020. 3. 26. 11:04
create table t1
(
	id int null,
	created_at datetime null,
	type int null,
	constraint t1_pk
		primary key (id)
);

create index idx_created_at
	on t1 (created_at);

create index idx_type
	on t1 (type);

 

이런 테이블이 있다.

show index from t1;

 

cardinality가

created_at : 300000

type : 4

 

일 때

 

select * from t1 where created_at >= '2020-03-26 00:00:00' and type = 1

을 하면 어떤 index를 탈까?

 

explain을 해본다면

idx_type은 const이고 idx_created_at는 range라서 idx_type을 탄다.

 

이 때는 fullscan과 다르지 않다.

 

select * from t1 use index (idx_created_at) where created_at >= '2020-03-26 00:00:00' and type = 1

는 idx_created_at을 타라고 hint를 줬기 때문에 cardinality가 더 높은 idx_created_at을 탈것이고

더 빠른 성능을 보여준다.

 

조금더 많은 컬럼과 index가 존재 할 때 hint를 두개 주면

상황에 따라 두개 중에 유리한것을 mysql이 선택한다.

 

예를 들면

type의 cardinality가 200000 이라면, 

type은 상수값으로 접근 하기 때문에 idx_type을 탈것이다.

 

정확한 내용은 아닐 수 있지만, 인덱스로 고생할 때 이 정보를 가지고 튜닝하다보면 좋은 결과를 얻는데 도움이 될 것이다.