简体   繁体   中英

SQL latest record per foreign_key

I've got the following 2 tables:

  • ingredients (id, name)
  • ingredient_prices (id, ingredient_id, price, created_at)

such that one ingredient can have many prices. What will be the best way to get the latest entered price per ingredient? I know it can be done easily with sub-selects, but I want to know if there is a more efficient way for doing it.

I do it this way:

SELECT i.*, p1.*
FROM ingredients i
 JOIN ingredient_prices p1 ON (i.id = p1.ingredient_id)
 LEFT OUTER JOIN ingredient_prices p2 ON (i.id = p2.ingredient_id 
   AND p1.created_at < p2.created_at)
WHERE p2.id IS NULL;

This searches for a price (p2) that is more recent than p1, and if none is found, then p1 must be the most recent price.

If there is a possibility of more than one price on a given date, then you need another term to filter out the duplicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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