简体   繁体   中英

How to sum all rating column values where recipe_id is distinct

To be more specific I have a table with recipes. In another table I keep ratings associated with these recipes. Each rating has an unique id, the second column is the recipe's id, the third column is the rating (from 1-5).

Expected result is the recipe_id, where all ratings associated with that recipe_id are the highest.

I hope you understand, I have no idea how to approach such query properly.

Hopefully I've posted my question properly, it's my first one.

You could use a self-join:

SELECT
  r.id,
  r.recipe_id,
  r.rating
FROM
  recipes_ratings r LEFT JOIN recipes_ratings r2
  ON r.recipe_id = r2.recipe_id
     AND r2.rating>r.rating
WHERE
  r2.rating IS NULL

Please see a fiddle here .

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