JOIN 关联字段类型不一致、隐式转换
SQL:
SELECT
a.id,
a.`name`,
a.update_time,
a.expire_duration,
a.isdefault,
a.isfree,
a.type,
a.env,
a.ecs,
b.id AS monitor_id,
a.user_id,
a.user_name,
a.provider_id,
a.manager,
a.contact,
a.dept
FROM
resource_pool a
LEFT JOIN monitor_resourcepool b
ON a.id = b.resourcepool_id
AND b.dr = 0
ORDER BY isfree DESC,
isdefault DESC,
a.update_time DESC;
执行较慢
我们查看执行计划
+----+-------------+-------+------+-------------------+------+---------+------+------+------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+-------------------+------+---------+------+------+------------------------------------------------+
| 1 | SIMPLE | a | ALL | NULL | NULL | NULL | NULL | 260 | Using filesort |
| 1 | SIMPLE | b | ALL | i_resourcepool_id | NULL | NULL | NULL | 361 | Range checked for each record (index map: 0x2) |
+----+-------------+-------+------+-------------------+------+---------+------+------+------------------------------------------------+
possible_keys = i_resourcepool_id ,但是 key = NULL, resourcepool_id 有索引,但是没有用到
原因是
a.`id` int(11) NOT NULL AUTO_INCREMENT,
b.`resourcepool_id` varchar(36) COLLATE utf8_bin NOT NULL DEFAULT '',
id 与 resourcepool_id 类型不符,隐式转换
JOIN 关联字段类型一定要相同。