从连接表中选择每组的最新数据

时间:2015-04-22 16:06:18

标签: mysql greatest-n-per-group

我有两张这样的表:

survey:
survey_id | store_code | timestamp

product_stock:
survey_id | product_code | production_month | value

如何根据调查时间戳获取最新值,并按store_code,product_code和production_month分组?

例如,如果我有

survey_id | store_code | timestamp
1           store_1      2015-04-20
2           store_1      2015-04-22
3           store_2      2015-04-21
4           store_2      2015-04-22

survey_id | product_code | production_month | value
1           product_1      2                  15
2           product_1      2                  10
1           product_1      3                  20
1           product_2      2                  12
3           product_2      2                  23
4           product_2      2                  17

它会像这样返回结果

survey_id | store_code | time_stamp | product_code | production_month | value
2           store_1      2015-04-22   product_1      2                  10
1           store_1      2015-04-20   product_1      3                  20
1           store_1      2015-04-20   product_2      2                  12
4           store_2      2015-04-22   product_2      2                  17

并且它需要尽可能快,看到数据库的大小非常大

1 个答案:

答案 0 :(得分:0)

更新 - 请再次运行查询

以下是我的回答:

SELECT survey.survey_id, survey.store_code, survey.timestamp, product_stock.survey_id, product_stock.product_code, product_stock.production_month, product_stock.value 
FROM survey 
INNER JOIN product_stock
ON survey.survey_id = product_stock.survey_id
WHERE survey.timestamp = (SELECT MAX(timestamp) 
               FROM survey)
GROUP BY survey.store_code,product_stock.product_code,product_stock.production_month;