1

以下查询对两个表进行操作: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 |       |
+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+

有什么建议么?

4

1 回答 1

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;
于 2012-08-18T01:34:06.430 回答