简体   繁体   English

如何获得 MySQL 中的最大值?

[英]How to get the MAX value in MySQL?

How to get the MAX value in every albumID(45, 12, 22, 8) in the following table?如何获取下表中每个专辑ID(45、12、22、8)的MAX值? I tried with this query.我试过这个查询。 But it returned me the first value, not max value.(3, 6, 5, 6)但它返回了我的第一个值,而不是最大值。(3、6、5、6)

SELECT
    *
FROM
    (
        SELECT
            *
        FROM
            contentnew
        WHERE
            genreID = 1
        ORDER BY
            albumID DESC,
            reg_count DESC
    ) AS newTB
GROUP BY
    albumID;

Look this看看这个

桌子

If I use the如果我使用

在此处输入图像描述

You can try你可以试试

select max(reg_count) from contentnew group by albumID

Once you group by, you can apply aggregate functions such as max on each group.分组后,您可以在每个组上应用聚合函数,例如 max。 In your example try:在您的示例中尝试:

SELECT albumID, max(reg_count) as max_count
FROM contentnew 
GROUP BY albumID

This will project each albumID with the max_count in the group.这将使用组中的 max_count 投影每个专辑 ID。 In the select statement you can only use aggregate functions.在 select 语句中,您只能使用聚合函数。 The reason why we are able to project (or print) albumID is because this is the column we grouped by.我们能够投影(或打印)albumID 的原因是因为这是我们分组的列。

Following comments:以下评论:

SELECT *
FROM contentnew as c1
WHERE c1.reg_count < (
    SELECT max(c2.reg_count)
    FROM contentnew as c2
    WHERE c1.albumID = c2.albumID
    GROUP BY c2.albumID)

You are almost there, one thing that might be helpful is to use row_number() function, if you want every column from the table.你快到了,如果你想要表格中的每一列,可能有用的一件事是使用 row_number() function。

with contentnew_test
as
(
select row_number() over (partition by albumId order by reg_count desc) row
,* from 
contentnew
)
select * from contentnew_test where row = 1 order by reg_count desc;

I used this as a reference as not sure about the syntax https://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/我将此用作参考,因为不确定语法https://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/

Subquery will give you a result set something like this:子查询会给你一个类似这样的结果集:

row albumId reg_count  ...
1   1        8         ...
2   1        7         ...
3   1        3         ...
4   1        1         ...
1   2        22        ...
2   2        9         ...
3   2        6         ...
4   2        1...and so on.

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

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