简体   繁体   中英

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? I tried with this query. But it returned me the first value, not max value.(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. 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. In the select statement you can only use aggregate functions. The reason why we are able to project (or print) albumID is because this is the column we grouped by.

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.

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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