简体   繁体   中英

how to select max value with corresponding id in mysql

SELECT 
    id
  , insId
  , MAX(avgRating) as avgRating 
FROM reviews 
WHERE status='1' 
GROUP BY insId

this query returns all reviews grouped by insId but id is not corresponding to this.

You need to use a self INNER JOIN to get the results you need.

SELECT
   reviews.id
 , reviews_max.insId
 , reviews_max.maxAvgRating
FROM (

  SELECT 
     insId
   , MAX(avgRating) AS maxAvgRating
  FROM
   reviews
  WHERE
   status = '1'
  GROUP BY
   insId
) AS reviews_max
INNER JOIN 
 reviews
ON
   reviews.insId = reviews_max.insId 
 AND
   reviews.avgRating = reviews_max.maxAvgRating

Try this:

SELECT 
    id
  , insId
  , MAX(avgRating) as avgRating 
FROM reviews 
WHERE status='1' 
GROUP BY id

You can try this out:

SELECT id, 
insId, 
MAX(avgRating) as avgRating 
FROM reviews 
WHERE status='1' 
GROUP BY id, insId

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