Skip to content
Advertisement

MySQL: retrieving the last record from each group and combining with the data of another table

There is a purchase table that information regarding the products bought. This will generate one one or more rows in the tStockMP table for each individual product bought.

Now, I need to display the table information for each product in stock. Since the purchase table contains the history of the changes, that information is in the highest keyid when grouped by purchase_id in the tPurchases table.

I’ve provided a complete script, here with example data describing my problem.

The I would need to “filter” the results so that ONLY the * rows remain in the final query, lest I need to do it by hand. But I don’t know how to modify my query and make this happen.

Advertisement

Answer

Never use commas in the FROM clause. I typical solution is to use a correlated subquery:

With an index on tPurchases(purchase_id, keyid), this often has the best performance.

If I approached this with window functions, I would phrase it as:

GMB has an alternative approach. If you have lots of data, it would be interesting to compare the performance of the two methods. I would advise the same index as above for all comparisons.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement