2

我有两个表成员和 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 |       |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
4

2 回答 2

6

问题是 MemberID_M 是 varchar 而 MemberID_t 是 INT

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

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

于 2012-10-23T15:42:45.707 回答
2

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

进一步的小问题,在您的主键中包含 NULL 值是否合乎逻辑?

于 2012-10-23T15:42:59.890 回答