开发者

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

  1. Total review count for each business Id
  2. 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


  1. select count(business Id) as total from reviews group by business Id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜