我不知所措。我有一个大约有 100K 行的表。查询该表时,结果通常很快,大约 2 毫秒左右。但每当我使用 ORDER BY 时,性能就会急剧下降到 120 毫秒左右。我读了MySQL ORDER BY 优化 http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html页面,但我不能说我理解一切。尤其是索引我不清楚。
最终我想运行以下查询:
SELECT *
FROM `affiliate_new_contracts`
WHERE phone_brand IN ('Apple','Blackberry','HTC','LG','Motorola','Nokia',
'Samsung','Sony Ericsson')
AND contract_length IN ('12','24')
AND (addon IS NULL OR addon IN('Telfort Sms 300','Surf & Mail'))
AND (plan_name = 'Telfort 100'
AND
credible_shop = 1
)
ORDER BY average_price_per_month ASC, phone_price_guestimate DESC,
contract_length ASC;
但如果我理解基本原理,我会很高兴。
删除上一个查询中的 ORDER BY 子句使其运行时间为 20 毫秒,而不是 120 毫秒。我有一个索引average_price_per_month
字段,但将 ORDER BY 子句简化为ORDER BY average_price_per_month
没有带来任何性能提升。我不明白。我对所谓的多列索引也一无所知,它应该能够帮助我完成最终的查询。
任何帮助,将不胜感激。我该如何让这个坏男孩表现出色?或者说这个追求是乌托邦式的?
The CREATE TABLE
语法如下:
$ show create table affiliate_new_contracts;
CREATE TABLE `affiliate_new_contracts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`plan_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`contract_length` int(11) DEFAULT NULL,
`phone_brand` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` float DEFAULT NULL,
`average_price_per_month` float DEFAULT NULL,
`phone_price_guestimate` float DEFAULT NULL,
`credible_shop` tinyint(1) DEFAULT '0',
`addon` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`addon_price` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_affiliate_new_contracts_on_plan_name` (`plan_name`),
KEY `index_affiliate_new_contracts_on_average_price_per_month` (`average_price_per_month`),
KEY `index_affiliate_new_contracts_on_price` (`price`)
) ENGINE=InnoDB AUTO_INCREMENT=2472311 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
顺便说一句,该表每周重新创建一次,同时不会更新。