我有一个 MySQL 问题。我必须优化网站上的一些查询。其中之一我已经完成了,但还有一些如果没有您的帮助我无法解决。
我有一个名为“新闻”的表:
CREATE TABLE IF NOT EXISTS `news` (
`id` int(10) NOT NULL auto_increment,
`edited` smallint(1) NOT NULL default '0',
`site` varchar(30) default NULL,
`foreign_id` varchar(25) default NULL,
`title` varchar(255) NOT NULL,
`text` text NOT NULL,
`image` varchar(255) default NULL,
`horizontal` smallint(1) NOT NULL,
`image_author` varchar(255) default NULL,
`text_author` varchar(255) default NULL,
`lang` varchar(3) NOT NULL,
`link` varchar(255) NOT NULL,
`date` date NOT NULL,
`redirect` smallint(1) NOT NULL,
`parent` int(10) NOT NULL,
`views` int(5) NOT NULL,
`status` smallint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `lang` (`lang`,`status`),
KEY `date` (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=47122 ;
如你所见,我有两个索引:“lang”和“date”
我尝试了不同索引的一些组合,这个组合给我带来了最好的结果......不幸的是仅在我的本地计算机上。在服务器上我仍然有不好的结果。我想说数据库是一样的。
查询:
SELECT id FROM news WHERE lang = 'en' AND STATUS =1 ORDER BY DATE DESC LIMIT 0, 10
本地主机解释:
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+------+---------+------+------+-------------+ | 1 | SIMPLE | news | index | lang | date | 3 | NULL | 23 | Using where | +----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
服务器说明:
+----+-------------+-------+------+---------------+--------+---------+-------------+-------+-----------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+--------+---------+-------------+-------+-----------------------------+ | 1 | SIMPLE | news | ref | status | status | 13 | const,const | 15840 | Using where; Using filesort | +----+-------------+-------+------+---------------+--------+---------+-------------+-------+-----------------------------+
我查看了很多其他类似的主题,但不幸的是我找不到任何可以在我的服务器上工作的解决方案。我将非常高兴为您提供一些解决方案并对此进行一些解释,以便我可以优化我的其他查询。
谢谢!
最佳答案
这是您的查询:
SELECT id
FROM news
WHERE lang = 'en' AND STATUS =1
ORDER BY DATE DESC
LIMIT 0, 10
最好的索引是包含查询中使用的所有字段(总共四个字段)的索引。索引中的排序是按照 where
子句中的相等条件进行的,后跟 order by
子句,最后是 select
子句中的其他列。
所以,尝试这个索引:ndws(leng, status, date, id)
。
关于MySQL优化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260964/