14

桌子:

CREATE TABLE `T1` (
  `UserId` int(10) unsigned NOT NULL,
  `FriendUserId` int(10) unsigned NOT NULL,
  `IsDisplayed` tinyint(1) unsigned NOT NULL,
  `Created` datetime NOT NULL,
  KEY `FriendUserId` (`FriendUserId`,`IsDisplayed`,`UserId`,`Created`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

查询:

SELECT `UserId`, `FriendUserId`, UNIX_TIMESTAMP(`Created`) AS `Created`
FROM `T1` WHERE `FriendUserId` = 22
  AND `IsDisplayed` = 0
  GROUP BY `UserId`
  ORDER BY `Created`

解释结果:

           id: 1
  select_type: SIMPLE
        table: T1
         type: ref
possible_keys: FriendUserId
          key: FriendUserId
      key_len: 5
          ref: const,const
         rows: 1
        Extra: Using where; Using index; Using temporary; Using filesort

问题:

如何优化它以便不使用临时表?

4

2 回答 2

12

MySQL文档说:

可以在以下条件下创建临时表:

如果有一个ORDER BY子句和一个不同的GROUP BY子句,或者如果ORDER BYorGROUP BY包含来自连接队列中第一个表以外的表的列,则会创建一个临时表。

因此,您只能通过删除来避免使用临时表order by Created

于 2012-08-10T06:22:17.910 回答
4

正如您可能理解的那样,问题在于对GROUP BY数据UserId进行排序,但结果集应按 ; 排序Created。因此,MySQL 将输出放在一个临时表中,对其进行排序并输出。

诀窍可能是强制Created一次按顺序输出不同的行。

我首先想到的是这样的:

SELECT DISTINCT
  UserId,
  FriendUserId,
  UNIX_TIMESTAMP(`Created`) AS `Created`
FROM T1
WHERE FriendUserId = 22 AND IsDisplayed = 0
ORDER BY `Created`

并将索引更改为(FriendUserId, IsDisplayed, Created, UserId).

或具有相同索引的另一个查询:

SELECT
  UserId,
  FriendUserId,
  UNIX_TIMESTAMP(`Created`) AS `Created`
FROM T1
WHERE FriendUserId = 22 AND IsDisplayed = 0
GROUP BY `Created`, UserId
于 2012-08-10T09:12:04.073 回答