2

我在索引这个左连接时遇到问题:

SELECT comments.id, comments.topid, comments.username, comments.body, comments.dt, comments.active, users.email
FROM comments
LEFT JOIN registered_users.users
ON comments.username = users.username
WHERE postid = 12 AND active = 1
ORDER BY id desc

我有以下索引:

Comments -> keyname (postid) - postid, active, id

用户 -> 键名(用户名) - 用户名

我回来的结果是:

+----+-------------+----------+------+---------------+--------+---------+-------------+------+---------------------------------+
| id | select_type | table    | type | possible_keys | key    | key_len | ref         | rows | Extra                           |
+----+-------------+----------+------+---------------+--------+---------+-------------+------+---------------------------------+
|  1 | SIMPLE      | comments | ref  | postid        | postid | 5       | const,const |  116 | Using temporary; Using filesort |
|  1 | SIMPLE      | users    | ALL  | NULL          | NULL   | NULL    | NULL        |    1 |                                 |
+----+-------------+----------+------+---------------+--------+---------+-------------+------+---------------------------------+

我该如何解决这个问题,这样我就不会“使用临时;使用文件排序”?

4

4 回答 4

1

如果其他人遇到此问题,请始终确保您的 JOIN 表设置为相同的排序规则类型。

我的评论表设置为“utf8_unicode_ci”——而我试图加入设置为“latin1_swedish_ci”的 users.email。

如果它们设置不同,MySQL 将无法使用任何索引。

我现在可以使用 ORDER BY、LIMIT 子句,而不会出现可怕的“文件排序”问题。

于 2013-07-16T16:41:48.660 回答
1

Perhaps making an index with all three columns

comments is an InnoDB table

ALTER TABLE comments ADD INDEX new_index (active,postid,username);

comments is a MyISAM table

ALTER TABLE comments ADD INDEX new_index (active,postid,id,username);

Why propose a new index?

Searching the comments table by the postid index will still require accessing the table intermittently to check the id and username columns. Having more columns from your WHERE and ORDER BY clauses inside the index will lighten the work for the Optimizer.

CAVEAT

Even if the retrieveal is a little faster, the filesort may be unavoidable because you said

ORDER BY id desc

Give it a Try !!!

于 2013-06-30T05:11:11.020 回答
0

经验告诉我这样做:

create index comments_postid on comments(postid);

你需要的另一个索引是,users(username)但你已经有了。

这样做也是一个好主意:

analyze table comments, users;
于 2013-06-30T09:06:03.500 回答
0

If active is a flag, there may not be enough selectivity for the optimizer to bother with it. Have you tried having the index only on postid?

于 2013-06-30T05:12:57.247 回答