简体   繁体   English

Mysql从表中选择每个唯一location_id和产品的日期最大值

[英]Mysql Select from table where a date is max for each unique location_id AND product

I have a table - records - that looks like this 我有一张表 - 记录 - 看起来像这样

id | location_id | product | stock | date  
===|=============|=========|=======|======
1  | Bakery 1    |  cake   |  21   | 2
2  | Bakery 1    |  bread  |  23   | 2
3  | Bakery 2    |  cake   |  21   | 2
4  | Bakery 2    |  bread  |  21   | 2
5  | Bakery 1    |  cake   |  21   | 3
6  | Bakery 1    |  bread  |  23   | 3
7  | Bakery 2    |  cake   |  21   | 3
8  | Bakery 2    |  bread  |  21   | 3
9  | Bakery 1    |  cake   |  21   | 4
10 | Bakery 1    |  bread  |  23   | 4
11 | Bakery 2    |  bread  |  23   | 4

For each location and for each product, i want to pick the row that has the highest date value. 对于每个位置和每个产品,我想选择具有最高日期值的行。 Which will look like ths 这将是什么样子

id | location_id | product | stock | date  
===|=============|=========|=======|======
7  | Bakery 2    |  cake   |  21   | 3
9  | Bakery 1    |  cake   |  21   | 4
10 | Bakery 1    |  bread  |  23   | 4
11 | Bakery 2    |  bread  |  23   | 4

How do i execute this with one query? 如何使用一个查询执行此操作? I could loop through all the locations and all the products and build the queries but its more time and memory consuming? 我可以循环遍历所有位置和所有产品并构建查询但是它的时间和内存消耗更多?

select r1.*
from records r1
join
(
  select location_id, product, max(date) as date
  from records
  group by location_id, product
) r2 on r1.location_id = r2.location_id 
    and r1.product = r2.product
    and r1.date = r2.date

If the following conditions are true you can do this job very efficiently using the id column 如果满足以下条件,则可以使用id列非常有效地完成此任务

  1. your id column is autoincrementing 你的id列是自动增量的
  2. the date column represents the current date: that is, you never insert a backdated record. date列表示当前日期:即,您永远不会插入回溯记录。
  3. you don't UPDATE the date column 你没有更新date

If these conditions are true, that means the unique identifier id can be used as a proxy for the non-unique value date for each record. 如果这些条件为真,则表示唯一标识符id可用作每条记录的非唯一值date的代理。 A row with a higher date value is always guaranteed to have a higher id value. 具有更高date值的行始终保证具有更高的id值。

If you can do this you can make your query perform very well. 如果您可以这样做,您可以使您的查询执行得非常好。

First, you create a subquery to get the id of the latest row for each combination of location and product. 首先,创建一个子查询,以获取每个位置和产品组合的最新行的id

SELECT MAX(id)
  FROM records
 GROUP BY location_id, date

Then you use that set of id values to pull the correct records from your table 然后使用该组id值从表中提取正确的记录

SELECT *
  FROM records
 WHERE id IN (
                SELECT MAX(id)
                 FROM records
                GROUP BY location_id, date
              )
ORDER BY location_id, product 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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