当使用派生查询进行连接时,MySQL慢速LEFT JOIN查询

时间:2012-08-18 01:30:17

标签: mysql sql

以下查询对两个表进行操作:dev_Profiledev_User

SELECT
  dev_Profile.ID AS pid,
  Name AS username,
  st1.online
FROM
  dev_Profile
  LEFT JOIN (
    SELECT 
      dev_User.ID, 
      lastActivityTime /* DATETIME */
    FROM
      dev_User)
    AS st1 ON st1.ID = dev_Profile.UserID;

每个表中大约有11K行,此查询需要大约6秒才能完成。我还没有很多数据库经验。我认为为dev_Profile.UserID创建一个索引可以解决问题,因为dev_Profile.ID已经有一个索引(它是PK)而dev_Profile.UserID没有索引,但是这没有帮助一点都不。

编辑:此查询的EXPLAIN输出:

+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+
| id | select_type | table       | type | possible_keys | key  | key_len | ref  | rows  | Extra |
+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+
|  1 | PRIMARY     | dev_Profile | ALL  | NULL          | NULL | NULL    | NULL | 11521 |       |
|  1 | PRIMARY     | <derived2>  | ALL  | NULL          | NULL | NULL    | NULL | 11191 |       |
|  2 | DERIVED     | dev_User    | ALL  | NULL          | NULL | NULL    | NULL | 11440 |       |
+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+

有什么建议吗?

1 个答案:

答案 0 :(得分:7)

为什么嵌套选择?这可能会使优化器混乱。尝试消除它:

SELECT
  dev_Profile.ID AS pid,
  Name AS username,
  st1.online
FROM
  dev_Profile
  LEFT JOIN dev_User st1 ON st1.ID = dev_Profile.UserID;