1

我不确定此查询是否使用索引。我该怎么说?

mysql> EXPLAIN SELECT au.* FROM users au WHERE au.id IN(SELECT fa.from_user_id FROM approvals fa INNER JOIN personas pp ON fa.persona_id = pp.id WHERE fa.to_user_id=1 AND pp.is_foundation=1 GROUP BY fa.from_user_id) ORDER BY id DESC LIMIT 0, 9999999999;
+----+--------------------+-------+--------+-----------------------+------------+---------+--------------------+------+----------------------------------------------+
| id | select_type        | table | type   | possible_keys         | key        | key_len | ref                | rows | Extra                                        |
+----+--------------------+-------+--------+-----------------------+------------+---------+--------------------+------+----------------------------------------------+
|  1 | PRIMARY            | au    | index  | NULL                  | PRIMARY    | 4       | NULL               | 2272 | Using where                                  |
|  2 | DEPENDENT SUBQUERY | fa    | ref    | to_user_id,persona_id | to_user_id | 4       | const              |  396 | Using where; Using temporary; Using filesort |
|  2 | DEPENDENT SUBQUERY | pp    | eq_ref | PRIMARY               | PRIMARY    | 4       | kjdb.fa.persona_id |    1 | Using where                                  |
+----+--------------------+-------+--------+-----------------------+------------+---------+--------------------+------+----------------------------------------------+
3 rows in set (0.00 sec)
4

3 回答 3

3

The key column in the output indicates the index that MySQL is using.

So yes, the query uses indexes.

You can read a lot more about the output of EXPLAIN in the MySQL documentation for the version of MySQL you are running. For example, if you're running MySQL 5.1, read http://dev.mysql.com/doc/refman/5.1/en/explain-output.html.

于 2012-07-15T06:14:39.770 回答
0

我会很快的。是的,用于连接,但不用于过滤记录。请查看额外字段。它应该在使用 where时“使用索引”,这确实更慢。

请考虑修改查询以避免子查询。

于 2012-07-15T06:29:02.110 回答
0

由@Trott 回答。

尽管我认为您非常有能力并且能够制定和尝试替代查询,但是 MySQL 的一个奇怪事实(很容易被监督):MySQL 长期以来声称 EXISTS 可以比 IN SELECT 更好地优化,作为当时寻求的元素在子查询内。

那将是最简单的形式:

EXPLAIN
  SELECT au.*
  FROM users au
  WHERE EXISTS
    (SELECT fa.from_user_id FROM approvals fa
    INNER JOIN personas pp ON fa.persona_id = pp.id
    WHERE fa.from_user_id = au.id
      AND fa.to_user_id=1 AND pp.is_foundation=1
    GROUP BY fa.from_user_id)
  ORDER BY id DESC
  LIMIT 0, 9999999999;
于 2012-07-15T06:32:11.820 回答