Group by,在MySQL中有使用

发布于 2024-12-25 11:10:39 字数 752 浏览 1 评论 0原文

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

评级|编号 |类

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 |编号 | class

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

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

当我使用 having

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

结果

老鼠 |编号 | 任何人

4.8 | 5 | salads
4.3 | 6 | dishes

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

I have problem with mysql query.
I need get full rows with max value rating.
For example I have table recipes

rating | id | class

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

And I get result:

rat | id | class

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

So in first row(where class='soup') I get trully max rating - 4.9, but in this row id has value 1, not 4.

When I use having

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

result become

rat | id | class

4.8 | 5 | salads
4.3 | 6 | dishes

Can anyone help me with this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最笨的告白 2025-01-01 11:10:39

尝试这个查询 -

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;

Try this query -

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;
就此别过 2025-01-01 11:10:39

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

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

One method is to use an IN() subquery to find the corresponding ids of the rows with MAX(rat).

SELECT * 
FROM recipes
WHERE id IN (
  SELECT id FROM recipes GROUP BY class HAVING rat = MAX(rat)
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文