简体   繁体   中英

MySQL optimize count query

I've got a question about MySQL performance. These are my tables:

(about 140.000 records)

CREATE TABLE IF NOT EXISTS `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `label` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
  `intro` text COLLATE utf8_unicode_ci NOT NULL,
  `content` text COLLATE utf8_unicode_ci NOT NULL,
  `date` int(11) NOT NULL,
  `active` int(1) NOT NULL,
  `language_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `indexed` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=132911 ;

(about 400.000 records)

CREATE TABLE IF NOT EXISTS `article_category` (
  `article_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

RUNNING THIS COUNT QUERY:

SELECT SQL_NO_CACHE COUNT(id) as total 
FROM (`article`) 
LEFT JOIN `article_category` ON `article_category`.`article_id` = `article`.`id` 
WHERE `article`.`language_id` = 1 
AND `article_category`.`category_id` = '<catid>'

This query takes a lot of resources, so I am wondering how to optimize this query. After executing it's beeing cached, so after the first run I am fine.

RUNNING THE EXPLAIN FUNCTION:

在此输入图像描述

AFTER CREATING AN INDEX:

ALTER TABLE `article_category` ADD INDEX ( `article_id` , `category_id` ) ;

在此输入图像描述

After adding indexes and changing LEFT JOIN to JOIN the query runs alot faster! Thanks for these fast replys :)

QUERY I USE NOW (I removed the language_id because it was not that neccesary):

SELECT COUNT(id) as total 
FROM (`article`) 
JOIN `article_category` ON `article_category`.`article_id` = `article`.`id` 
AND `article_category`.`category_id` = '<catid>'

I've read something about forcing an index, but I think thats not neccesary anymore because the tables are already indexed, right?

Thanks alot!

Martijn

You haven't created necessary index on the table

Table article_category - Create a compound index on (article_id, category_id)

Table article -Create a compound index on (id, language_id)

If this doesn't help post the explain statement.

JOIN条件中使用的列应该有索引,因此您需要索引article_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM