我有下表
CREATE TABLE `prod_prices` (
`id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
`price` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
还有一些样本数据
INSERT INTO `prod_prices` (`id`, `date`, `price`) VALUES
('plan_a', '2012-06-15', 10.20),
('plan_a', '2012-06-16', 10.30),
('plan_b', '2012-06-15', 5.20),
('plan_b', '2012-06-16', 5.30),
('plan_b', '2012-06-17', 5.50);
并想知道每个计划的最新价格。我有以下查询
SELECT p1.id, p1.date, p1.price
FROM prod_prices p1
LEFT JOIN prod_prices p2 ON p1.id = p2.id
AND p1.date < p2.date
WHERE p2.id IS NULL
虽然产生了非常糟糕的性能,但它确实有效。 EXPLAIN
节目
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE p1 ALL NULL NULL NULL NULL 5
1 SIMPLE p2 ref PRIMARY PRIMARY 98 p1.id 1 Using where; Using index; Not exists
因此p1
表选择不使用任何索引。什么事?