我有一个MySQL表:
结构:
内容:
我需要进行此查询:
SELECT * FROM line WHERE id_user='879930883' AND dt IS NOT NULL ORDER BY dt DESC LIMIT 6
id_user
总是与众不同。此查询大约需要2秒钟。
如何更快地进行查询?
修改 这是EXPLAIN SELECT * FROM行的输出WHERE id_user =' 879930883'和dt是非空的顺序由dt DESC限制6:
CREATE TABLE `line` (
`id_line` int(11) NOT NULL AUTO_INCREMENT,
`id_media` varchar(128) NOT NULL,
`img` varchar(256) NOT NULL,
`feed` tinyint(1) NOT NULL DEFAULT '0',
`tag` varchar(32) NOT NULL,
`done` tinyint(1) NOT NULL DEFAULT '0',
`id_user` int(11) NOT NULL,
`dt` datetime NOT NULL,
PRIMARY KEY (`id_line`),
KEY `idx_line_3` (`id_user`,`dt`)
) ENGINE=MyISAM AUTO_INCREMENT=620793 DEFAULT CHARSET=utf8
答案 0 :(得分:4)
您可以通过创建索引来加快速度。在这种情况下:
create index idx_line_3 on line(id_user, done, dt);
编辑:
对于查询:
SELECT *
FROM line
WHERE id_user = '879930883' AND dt IS NOT NULL
ORDER BY dt DESC
LIMIT 6 ;
您需要以下索引:
create index idx_line_2 on line(id_user, dt);
但是,我并不是100%确定它会使用order by
的索引,因此请检查explain
计划以查询该查询。如果它正在进行文件排序,那么您可以通过过滤NULL
值第二个来修复查询:
SELECT l.*
FROM (SELECT l.*
FROM line l
WHERE id_user = '879930883'
ORDER BY dt DESC
LIMIT 6
) l
WHERE dt IS NOT NULL
ORDER BY dt DESC;
order by dt desc
将NULL
值放在最后。