我有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
任何人都可以帮我解决这个问题吗?
答案 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;