繁体   English   中英

通过在MySQL中使用进行分组

[英]Group by, having using in MySQL

我对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

我得到结果:

老鼠 id |

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

因此,在第一行(其中class ='soup')中,我得到的最高评分是4.9,但在这一行中,id的值为1,而不是4。

当我使用具有

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

结果变成

老鼠 id |

4.8 | 5 | salads
4.3 | 6 | dishes

谁能帮助我解决这个问题?

一种方法是使用IN()子查询来查找具有MAX(rat)的行的对应id

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

试试这个查询-

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM