I have the next problem in Postgres.
I have products with reviews, each review has votes.
So here are two tables, a "votes" table and a "reviews" table:
Table "votes"
Column | Type | KEYS
-----------+---------+----------------------------------------------------
id | integer |
user_id | integer | FK to users table
review_id | integer | FK to reviews table
Table "reviews"
Column | Type | KEYS
------------+-----------------------------+--------------------------------------
id | integer |
product_id | integer | FK to products
user_id | integer | FK to users
I would like to get the reviews with most votes for each product. In other words, I need to get the review_id that has the maximun number of votes for each product.
Here is the query I am using:
SELECT max(votes_per_review.votes), reviews.product_id
FROM (SELECT count(*) AS votes,review_id FROM votes GROUP BY review_id) AS votes_per_review, reviews
WHERE votes_per_review.review_id = reviews.id
GROUP BY reviews.product_id
I get the number of votes for the most popular review for each product and the product id, but I am not getting the review_id.
I know that you can think that this question is resolved in StackOverflow like here. However I can't resolve this problem with that post or trying to use OVER PARTITION.
Thanks and sorry in advance if the question is resolved in StackOverflow.