2015-04-22 24 views
2

我有兩個表是這樣選擇每個組最新數據:連接表

survey: 
survey_id | store_code | timestamp 

product_stock: 
survey_id | product_code | production_month | value 

我怎樣才能獲得最新值的基礎上,調查時間戳與store_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 

,它必須儘可能快,眼看着數據庫的大小

相當大
+0

你是什麼意思的「獲取最新的價值,基於調查時間戳」?我不明白你的問題的這一部分。 –

+0

不好意思的英語,不是母語......我的意思是根據調查的時間戳列選擇最新的行。 – raven

+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; 
+0

它似乎返回0行,如果我包含where子句,並且如果我將它取出它返回每個組的第一次出現 – raven

+0

已更新 - 請再次運行查詢。 –