分组,在MySQL中使用

时间:2012-01-05 14:32:04

标签: mysql group-by

我有mysql查询的问题。 我需要获得具有最大值评级的完整行。  例如,我有表食谱

评分| id |类

4.1  | 1 | soup
4.2 | 3 | soup
4.9 | 4 | soup
4.8 | 5 | salads
4.3 | 6 | dishes9

SELECT MAX(rating) rat, id, class FROM recipes GROUP BY class

我得到了结果:

rat | id |类

4.9 | 1 | soup
4.8 | 5 | salads
4.3 | 6 | dishes

所以在第一行(其中class ='soup')我得到trully max rating - 4.9,但是在这行中id的值为1,而不是4。

当我使用

SELECT MAX(rating) rat, id, class FROM recipes GROUP BY class HAVING rating=rat

结果变成

rat | id |类

4.8 | 5 | salads
4.3 | 6 | dishes

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

一种方法是使用IN()子查询来查找id行的相应MAX(rat)个。

SELECT * 
FROM recipes
WHERE id IN (
  SELECT id FROM recipes GROUP BY class HAVING rat = MAX(rat)
)

答案 1 :(得分:0)

尝试此查询 -

SELECT r1.*  FROM recipes r1
  JOIN (SELECT MAX(rating) rat, class FROM recipes GROUP BY class) r2
    ON r1.class = r2.class AND r1.rating = r2.rat;