mysql 복합키 순서(range 조건시)

junsangyu·2025년 1월 25일

mysql에서 쿼리를 작성하다가 복합키 인덱스를 타지 않는 문제가 발생했다.

SELECT a.cid a_cid, b.cid b_cid, COUNT(*) inter
FROM chat a
JOIN chat b ON a.uid=b.uid AND a.cid<b.cid
GROUP BY a.cid, b.cid

해당 쿼리를 보면 JOIN ON 부분에서 uid 동등 조건과 cid 범위 조건으로 필터링 하는걸 볼 수 있다.

이 때 mysql은 동등 조건을 먼저 확인하고 범위 조건을 마지막에 확인한다.

그래서 복합키를 (uid, cid) 처럼 동등 조건을 먼저 위치하고 범위 조건을 나중에 작성하면 정상적으로 인덱스를 타는 것을 볼 수 있다

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+------------------------------------------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra                                          |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+------------------------------------------------+
|  1 | SIMPLE      | a     | NULL       | index | PRIMARY       | PRIMARY | 1022    | NULL |  117 |   100.00 | Using index                                    |
|  1 | SIMPLE      | b     | NULL       | ALL   | PRIMARY       | NULL    | NULL    | NULL |  117 |    33.33 | Range checked for each record (index map: 0x1) |
+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+------------------------------------------------+

참고 링크
https://planetscale.com/learn/courses/mysql-for-developers/indexes/composite-indexes
https://dba.stackexchange.com/questions/153156/how-to-use-composite-index-in-range-query-in-mysql

profile
👨🏻‍💻

0개의 댓글