简体   繁体   中英

Awful MySQL LEFT JOIN Performance for groupwise maximum

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.

SELECT  p1.*
FROM    prod_prices p1
        INNER JOIN
        (   SELECT  ID, MAX(Date) AS Date
            FROM    prod_prices
            GROUP BY ID
        ) AS p2
            ON p1.ID = p2.ID 
            AND p1.Date = p2.Date

Try this

SELECT p1.id, p1.date, p1.price
FROM prod_prices p1
Where p1.id NOT IN 
(Select id fro prod_prices p2 where p2.date>p1.date)

i would recomend something like this.

Get the latest date

select max(date) date,id group by id

Now select matching records by joining above query.

SELECT p1.id, p1.date, p1.price
FROM prod_prices p1 a,
(select max(date) date,id group by id) p2
where p1.id=p2.id and p1.date = p2.date

this will give you the latest price provided you have one price for one product in a day.

The performance was low as your search criteria involves Date fields and fields containing Null value which forces a table scan.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM