简体   繁体   中英

How can i optimize this following mysql query

Can anyone tune this query for better performance ?

SELECT `Vocabulary`.`id`,
`Vocabulary`.`title`,
`Vocabulary`.`alias`,
`Vocabulary`.`description`,
`Vocabulary`.`required`,
`Vocabulary`.`multiple`,
`Vocabulary`.`tags`,
`Vocabulary`.`plugin`,
`Vocabulary`.`weight`,
`Vocabulary`.`updated`,
`Vocabulary`.`created`,
`TypesVocabulary`.`id`,
`TypesVocabulary`.`type_id`,
`TypesVocabulary`.`vocabulary_id`,
`TypesVocabulary`.`weight` 
FROM `epowerg`.`vocabularies` AS `Vocabulary` 
JOIN `epowerg`.`types_vocabularies` AS `TypesVocabulary` 
ON (`TypesVocabulary`.`type_id` IN (1, 2, 4) 
AND `TypesVocabulary`.`vocabulary_id` = `Vocabulary`.`id`)    
ORDER BY `Vocabulary`.`weight` ASC;

Result generated from query :

+----+-------------+-----------------+------+---------------+------+---------+------+------+---------------------------------+
| id | select_type | table           | type | possible_keys | key  | key_len | ref  | rows | Extra                           |
+----+-------------+-----------------+------+---------------+------+---------+------+------+---------------------------------+
|  1 | SIMPLE      | Vocabulary      | ALL  | PRIMARY       | NULL | NULL    | NULL |    2 | Using temporary; Using filesort |
|  1 | SIMPLE      | TypesVocabulary | ALL  | NULL          | NULL | NULL    | NULL |    4 | Using where; Using join buffer  |
+----+-------------+-----------------+------+---------------+------+---------+------+------+---------------------------------+

Thanks in advance Prabhakaran. R

Here is the structure of your query:

select v.*, tv.*
from `epowerg`.`vocabularies` v JOIN
     `epowerg`.`types_vocabularies` tv
     ON tv.type_id IN (1, 2, 4) AND      
        tv.vocabulary_id = v.id    
ORDER BY v.weight ASC; 

There are basically two possible execution plans for this query: reading v first and looking up values in tv . Or reading tv and looking up values in v .

For the first, you want indexes on vocabularies(weight, id) and types_vocabularies(vocabulary_id, type_id) . If this works, then it will eliminate the sort.

The second approach to try is filtering on the types first. The indexes for this are: types_vocabularies(type_id, vocabulary_id) and vocabularies(id) .

Which method is better depends on the nature of your data. But try the first first, because eliminating the sort is often a good idea.

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