Top record per each foreign key in MySQL
I have a table in MySQL which has following columns
Table - Reviews
Review_Id
Business_Id
Title
Description
Useful_Count
A particular business_id (foreign key) can have many reviews. What I want is to extract this information from DB given a set of busi开发者_运维问答ness Ids
- Total review count for each business Id
- The top review (title and description mainly) for each business Id (Top review would be the one having highest number of useful_counts.
Is it possible to get both the information using a single SQL query?
Try this:
SELECT r.Business_Id, t.c AS 'Number of Reviews',
r.Title, r.Description, t.max_useful_count
FROM Reviews r
JOIN (SELECT Business_Id, COUNT(Business_Id) AS c,
MAX(Useful_Count) AS max_useful_count
FROM Reviews
WHERE r.Business_Id IN (...)
GROUP BY Business_Id) as t
ON r.Business_Id = t.Business_Id
AND r.Useful_Count = t.max_useful_count
- select count(business Id) as total from reviews group by business Id
精彩评论