mysql - Select latest data per group from joined tables -


i have 2 tables this:

survey: survey_id | store_code | timestamp  product_stock: survey_id | product_code | production_month | value 

how can latest value, based on survey timestamp , grouped store_code, product_code, , production_month?

for example if have

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 

it'd return result this

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 

and needs fast possible, seeing database quite large in size

updated - please run query again

here answer:

select survey.survey_id, survey.store_code, survey.timestamp, product_stock.survey_id, product_stock.product_code, product_stock.production_month, product_stock.value  survey  inner join product_stock on survey.survey_id = product_stock.survey_id survey.timestamp = (select max(timestamp)                 survey) group survey.store_code,product_stock.product_code,product_stock.production_month; 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -