Answer the question
In order to leave comments, you need to log in
mysql. Whether it is necessary to put indexes on fields which participate in ORDER BY?
Data: declaration table
CREATE TABLE IF NOT EXISTS `blurb_topics` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`poster` varchar(200) NOT NULL,
`poster_id` int(10) unsigned NOT NULL DEFAULT '0',
`subject` varchar(255) NOT NULL, # заголовок
`posted` int(11) unsigned NOT NULL DEFAULT '0', # время поста, timestamp
`forum_id` int(10) unsigned NOT NULL DEFAULT '0', # id подкатегории
`cat_id` int(11) NOT NULL DEFAULT '0', # id категории
`sticky` int(11) unsigned NOT NULL DEFAULT '0', # "закрепление" в топе на первом месте, timestamp
'deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
`fliped` int(11) unsigned NOT NULL, # время "подбросить" объявления, timestamp
`path` varchar(300) DEFAULT NULL,
`separated` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `topics_forum_id_idx` (`forum_id`),
KEY `cat_id` (`cat_id`),
KEY `poster_id` (`poster_id`),
KEY `posted` (`posted`,`sticky`,`fliped`),
KEY `deleted` (`deleted`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;
SELECT * blurb_topics WHERE deleted=0 ORDER BY (sticky > 0) DESC, fliped DESC, posted DESC LIMIT 0, 50 ');
Answer the question
In order to leave comments, you need to log in
It's all about the condition (sticky > 0), it is this condition that prevents the use of the index.
It might make sense to sticky enum('no', 'yes') and sticky_timestamp and use that sticky.
Mysql does not use indexes if ORDER BY is performed on different columns.
Proof: dev.mysql.com/doc/refman/5.1/en/order-by-optimization.html - everything is written in detail
you can create a cron job (something similar to Oracle Materialized View), which every ten minutes will recalculate those advertisements that are in the top and save the precalculated IDs to another table.
CREATE TABLE `top_topics` (
`blurb_topics_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`blurb_topics_id`),
}
Then just join with the original table.
The use of an index in mysql also depends on the order of the columns in the index. That is, `posted`+`sticky`+`fliped`+`deleted` will not be used, but `deleted`+`sticky`+`fliped`+`posted` can and will be ( How MySQL optimizes ORDER BY )
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question