mysql选择查询非常慢并使用filesort

时间:2014-09-28 13:14:40

标签: mysql performance select

我在慢查询选择中有一个大问题 0.3054秒

这个查询

SELECT id, ar_name, en_name,product_id,havproduct, viewnum, uid,pin_to, sid, ssid,cid, close,date
FROM subject
where active = '1' and deleted = '0' and cid= '24'
order by id DESC
LIMIT 0,30

当我使用这个

explain

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   SIMPLE  subject     ALL     NULL    NULL    NULL    NULL    230026  Using where; Using filesort

并且此表创建

CREATE TABLE `subject` (
  `id` int(11) NOT NULL,
  `cid` int(11) NOT NULL,
  `did` int(11) NOT NULL,
  `sid` int(11) NOT NULL,
  `ssid` int(11) NOT NULL,
  `product_id` int(11) NOT NULL DEFAULT '0',
  `havproduct` int(11) NOT NULL DEFAULT '0',
  `uid` int(11) NOT NULL,
  `ar_name` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `en_name` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `close` int(11) NOT NULL DEFAULT '0',
  `active` int(11) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `viewnum` int(11) NOT NULL DEFAULT '1',
  `pin_to` int(11) NOT NULL DEFAULT '0',
  `deleted` int(11) NOT NULL,
  `user_active` int(11) NOT NULL DEFAULT '1',
  `dep_active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM DEFAULT CHARSET=utf8

并且该表具有200000条记录或更多来自数据

1 个答案:

答案 0 :(得分:0)

您的数据没有密钥。对于您的特殊查询,最佳索引是:

create index id_subject_4 on subject(active, deleted, cid, id)

顺便说一句,你应该只对字符串和日期常量使用单引号。查询中的所有值都是整数,因此请删除引号:

SELECT id, ar_name, en_name,product_id,havproduct, viewnum, uid, pin_to, sid, ssid,cid, close,date
FROM subject
where active = 1 and deleted = 0 and cid = 24
order by id DESC
LIMIT 0, 30;