即使在索引之后,MySQL也会加速缓慢

时间:2012-10-23 15:38:21

标签: mysql performance left-join

我有两个表成员和dep,其描述如下:

TABLE members:
+-----------------+------------+------+-----+---------+-------+
| Field           | Type       | Null | Key | Default | Extra |
+-----------------+------------+------+-----+---------+-------+
| MemberID_M      | varchar(8) | YES  | MUL | NULL    |       |
| Age             | varchar(5) | YES  |     | NULL    |       |
| Sex             | varchar(1) | YES  |     | NULL    |       |
| SomeInfo        | int(11)    | YES  |     | NULL    |       |
+-----------------+------------+------+-----+---------+-------+
TABLE dep:
+-----------------+------------+------+-----+---------+-------+
| Field           | Type       | Null | Key | Default | Extra |
+-----------------+------------+------+-----+---------+-------+
| MemberID_t      | int(11)    | YES  | MUL | NULL    |       |
| YEAR            | varchar(2) | NO   |     |         |       |
| Days            | tinyint(4) | YES  |     | NULL    |       |
| train           | bigint(20) | NO   |     | 0       |       |
+-----------------+------------+------+-----+---------+-------+

我想执行以下查询:

CREATE TABLE table2 
SELECT a.*,b.* 
FROM dep AS a LEFT OUTER JOIN members AS b 
          ON  a.MemberID_t = b.Memberid_M;

最初,两个表中的ID都没有编入索引,查询也没有返回几个小时。现在,即使在索引之后也需要花费很多时间。

EXPLAIN for the SELECT part of the query is:
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
|  1 | SIMPLE      | a     | ALL  | NULL          | NULL | NULL    | NULL | 436689 |       |
|  1 | SIMPLE      | b     | ALL  | memid2        | NULL | NULL    | NULL | 226127 |       |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+

2 个答案:

答案 0 :(得分:5)

问题是MemberID_M是varchar而MemberID_t是INT

此字段的转换是为什么需要这么长时间

为获得最佳效果,关键字段必须是相同的类型

答案 1 :(得分:2)

您正在加入基于不同类型的列。一个是INT而另一个是VARCHAR。这可能会导致大量时间花在转换上(如果MySQL也会忽略基于此的键,也不确定)。

进一步的重点是,在看似是主键的情况下使用NULL值是否合乎逻辑?