如何在mysql中选择具有相应id的最大值

时间:2018-06-11 12:43:16

标签: mysql

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

此查询返回按insId分组的所有评论,但id与此不对应。

3 个答案:

答案 0 :(得分:1)

您需要使用自我INNER JOIN来获得所需的结果。

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

你可以尝试一下:

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