您好,登錄后才能下訂單哦!
慢SQL日志里看到一個三張表的關聯查詢,如下:
SELECT COUNT(1) FROM refund_order_item i, artisan a, user u WHERE u.userid = i.user_id AND a.artisan_id = i.artisan_id;
測試查詢時間:
mysql> SELECT COUNT(1) -> FROM refund_order_item i, artisan a, user u -> WHERE u.userid = i.user_id -> AND a.artisan_id = i.artisan_id; +----------+ | COUNT(1) | +----------+ | 260605 | +----------+ 1 row in set (2.30 sec)
查看執行計劃:
mysql> explain SELECT COUNT(1) -> FROM refund_order_item i, artisan a, user u -> WHERE u.userid = i.user_id -> AND a.artisan_id = i.artisan_id; +----+-------------+-------+------------+--------+----------------------------+---------+---------+------------------+--------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+--------+----------------------------+---------+---------+------------------+--------+----------+-------------+ | 1 | SIMPLE | i | NULL | ALL | idx_user_id,idx_artisan_id | NULL | NULL | NULL | 255599 | 100.00 | NULL | | 1 | SIMPLE | a | NULL | eq_ref | PRIMARY | PRIMARY | 122 | hlj.i.artisan_id | 1 | 100.00 | Using index | | 1 | SIMPLE | u | NULL | eq_ref | userid | userid | 122 | hlj.i.user_id | 1 | 100.00 | Using index | +----+-------------+-------+------------+--------+----------------------------+---------+---------+------------------+--------+----------+-------------+
可以看到refund_order_item表沒有走索引。
創建聯合索引:
ALTER TABLE refund_order_item ADD INDEX idx_aid_uid (artisan_id, user_id);
查看執行計劃:
explain SELECT COUNT(1) FROM refund_order_item i, artisan a, user u WHERE u.userid = i.user_id AND a.artisan_id = i.artisan_id; +----+-------------+-------+------------+--------+----------------------------------------+-------------+---------+------------------+--------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+--------+----------------------------------------+-------------+---------+------------------+--------+----------+-------------+ | 1 | SIMPLE | i | NULL | index | idx_user_id,idx_artisan_id,idx_aid_uid | idx_aid_uid | 244 | NULL | 255599 | 100.00 | Using index | | 1 | SIMPLE | a | NULL | eq_ref | PRIMARY | PRIMARY | 122 | hlj.i.artisan_id | 1 | 100.00 | Using index | | 1 | SIMPLE | u | NULL | eq_ref | userid | userid | 122 | hlj.i.user_id | 1 | 100.00 | Using index | +----+-------------+-------+------------+--------+----------------------------------------+-------------+---------+------------------+--------+----------+-------------+
可以看到執行計劃已經走索引。
測試查詢時間:
mysql> SELECT COUNT(1) -> FROM refund_order_item i, artisan a, user u -> WHERE u.userid = i.user_id -> AND a.artisan_id = i.artisan_id; +----------+ | COUNT(1) | +----------+ | 260605 | +----------+ 1 row in set (1.15 sec)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。