I have the following table
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;
And some sample data
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);
And want to know the latest price for each plan. I have the following query
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
which works, although yields truly abysmal performance. EXPLAIN shows
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
and hence the p1 table select is not using any indices. What is the matter?
This should give the same results and perform much better.