by 음미 [SQL Query] MySQL 인덱스 [2021.08.12 21:47:57]
SELECT `bulbs`.* FROM `bulbs` INNER JOIN `likes` ON `bulbs`.`id` = `likes`.`target_id` WHERE `likes`.`user_id` = (유저번호) AND `likes`.`target_type` = 'Bulb'
안녕하세요. 쿼리문은 같은데 where value만 다를때 인덱스가 완전히 다르게 타는 케이스가 있어서 혹시 짐작가시는 이유가 있을까 해서 여쭤보러 왔습니다 ㅜㅜ mysql 5.7을 사용하고 있습니다.
indexing은 (user_id, target_id, target_type)으로 설정되어있어요.
user_id가 23이 아니라 49 일때는 const로 인덱싱이 잘 타는데요.
id|select_type|table |type|possible_keys |key |key_len|ref |rows|Extra |
--+-----------+-------+----+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------+-------+-----+----+-------------------------------------------------------------+
1|SIMPLE | likes| ref | index_likes_on_user_id_and_target_id_and_target_type | index_likes_on_user_id_and_target_id_and_target_type| 4 | const| 21 | Using where; Using index |
user_id 23일때는 인덱스 풀 스캔을 합니다.
id|select_type|table |type |possible_keys |key |key_len|ref|Extra |rows |
--+-----------+-------+-----+-----------------------------------------------------------------------------------------------------------+------------------------------------------------------+-------+---+------------------------------------------------+---------+
1| SIMPLE | likes| index| index_likes_on_user_id_and_target_id_and_target_type | index_likes_on_user_id_and_target_id_and_target_type| 775 | | Using where; Using index | 9356|
해당 23번 user가 like를 많이 한건가 싶어서 찾아봤더니 49번유저와 거의 비슷하게( 49번 유저는 21번, 21번 유저는23번) like를 했더라고요(인덱스 탈 column에 null 데이터도 없어요) 그런데, 23번 유저만 모든 테이블의 row를 다 스캔해서 매우 이상합니다.
혹시 짚이시는 원인이 있을까요? 키워드라도 알려주시면 열심히 찾아보겠습니다 ㅜㅜ