Mysql
即使有索引,MySQL 查詢也很慢
我的桌子的結構
mysql> show create table t_group_tag_relation\G *************************** 1. row *************************** Table: t_group_tag_relation Create Table: CREATE TABLE `t_group_tag_relation` ( `id` int(11) NOT NULL AUTO_INCREMENT, `domain_id` int(11) NOT NULL, `group_tag_id` int(11) NOT NULL, `resource_id` int(11) NOT NULL, `resource_type` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `group_tag_id_resource_id` (`group_tag_id`,`resource_id`), KEY `domain_id` (`domain_id`,`group_tag_id`,`resource_type`,`resource_id`), KEY `domain_id_resource_type` (`domain_id`,`resource_type`) ) ENGINE=InnoDB AUTO_INCREMENT=1613462 DEFAULT CHARSET=latin1 1 row in set (0.03 sec)
解釋我的查詢計劃
mysql> explain select * from t_group_tag_relation WHERE resource_id = 575868070 AND domain_id = 476 AND resource_type = 2; +----+-------------+----------------------+------+-----------------------------------+-----------+---------+-------+-------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+----------------------+------+-----------------------------------+-----------+---------+-------+-------+--------------------------+ | 1 | SIMPLE | t_group_tag_relation | ref | domain_id,domain_id_resource_type | domain_id | 4 | const | 28400 | Using where; Using index | +----+-------------+----------------------+------+-----------------------------------+-----------+---------+-------+-------+--------------------------+ 1 row in set (0.57 sec)
它已經在使用索引,但性能不佳。如何提高性能?
我認為您的解釋計劃正在進行繁重的索引掃描。您可能需要的是包含這三列的索引。
請創建此索引
ALTER TABLE t_group_tag_relation ADD INDEX resource_id_domain_id_resource_type_index (resource_id,domain_id,resource_type);
並再次嘗試您的查詢。
‘domain_id_resource_type’ 索引的基數可能低於 ‘domain_id’ 的基數。您可以嘗試跳過優化器選擇並使用提示聲明使用“domain_id_resource_type”而不是“domain_id
USE INDEX
”:SELECT * FROM t_group_tag_relation USE INDEX(domain_id_resource_type) WHERE resource_id = 575868070 AND domain_id = 476 AND resource_type = 2;
請注意,
USE INDEX
預計將在未來的 MySQL 版本中棄用,並且可以替換INDEX
為 MySQL 8.0.20 版本。(這不適用於 MariaDB。)