mysql – 更改ORDER BY方向会导致性能问题

我使用MySQL 5.6,我有两个表,每个表有16M行:

CREATE TABLE IF NOT EXISTS `newsstudios` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16855382 ;

CREATE TABLE IF NOT EXISTS `newsstudio_categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `newsstudio_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `newsstudio_id` (`newsstudio_id`),
  KEY `category_id` (`category_id`),
  KEY `newsstudio_id_category_id` (`newsstudio_id`,`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16864013 ;

我有一个查询按订单顺序由newsstudios.id ASC:

SELECT SQL_NO_CACHE id FROM `newsstudios` WHERE exists 
(
  select newsstudio_id from newsstudio_categories 
  where newsstudios.id=newsstudio_categories.newsstudio_id 
  and newsstudio_categories.category_id in (1303,1313,1323,1333,1343,632)
) 
order by newsstudios.id limit 5;

此查询的结果是:

+------+
| id   |
+------+
|   27 |
|   47 |
|   87 |
|  110 |
|  181 |
+------+
5 rows in set (0.19 sec)

但是当我将订单方向更改为DESC时,查询执行时间减少了100次:

+------+
| id   |
+------+
| 98232|
| 98111|
| 95222|
| 88132|
| 78181|
+------+
5 rows in set (21 sec)

第一:为什么这会因为性能的巨大差异而改变顺序方向?

第二:在此查询之前,我尝试了LEFT JOIN和WHERE IN查询而不是WHERE EXISTS但是它们有重复的结果我应该使用GROUP BY它导致使用filesort并使用临时性能会大大降低性能.您对查询有什么建议可以获得更好的性能吗?

最佳答案
如果你正在搜索的不同类别不是很多,你可以构建更复杂的查询,这将使用索引(category_id,newsstudio_id),我希望它比你之前的查询更有效,使用ASC或DESC选择.

构建起来有点复杂,如果类别数量为数十或数百,我预计效率会降低:

SELECT newsstudio_id
FROM 
  ( ( SELECT newsstudio_id  FROM newsstudio_categories  WHERE category_id = 1303
      ORDER BY newsstudio_id DESC  LIMIT 5 
    ) 
    UNION 
    ( SELECT newsstudio_id  FROM newsstudio_categories  WHERE category_id = 1313
      ORDER BY newsstudio_id DESC  LIMIT 5 
    )
      ...
    UNION
    ( SELECT newsstudio_id  FROM newsstudio_categories  WHERE category_id = 632
      ORDER BY newsstudio_id DESC  LIMIT 5 
    )
  ) AS tmp
ORDER BY newsstudio_id DESC
LIMIT 5 ;

转载注明原文:mysql – 更改ORDER BY方向会导致性能问题 - 代码日志