MYSQL: Add a column to result which contains whether this rows contain max number of a particular column or not

I am using MySQL 5.7 and My Table is:

cp_idcp_namecp_versioncp_parent_id
1playlist111
2playlist121
3playlist131
4playlist214
5playlist224
6playlist316
7playlist326
8playlist336
9playlist419

As you can see from the table that:

  1. A single playlist can have more than one version but will have the same parent id.

Result I Require is:
I want to add a column to the result which contains whether that row is the cp version row or not.

cp_idcp_namecp_versioncp_parent_idmax_version
1playlist1110
2playlist1210
3playlist1311
4playlist2140
5playlist2241
6playlist3160
7playlist3260
8playlist3361
9playlist4191

Thanks, In Advance

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

On MySQL 8+ we can use MAX as an analytic function:

SELECT *, MAX(cp_version) OVER (PARTITION BY cp_parent_id) = cp_verson AS max_version
FROM yourTable
ORDER BY cp_id;

On earlier versions of MySQL we can use a join approach:

SELECT t1.*, t2.cp_version_max = t1.cp_version AS max_version
FROM yourTable t1
INNER JOIN
(
    SELECT cp_parent_id, MAX(cp_version) AS cp_version_max
    FROM yourTable
    GROUP BY cp_parent_id
) t2
    ON t2.cp_parent_id = t1.cp_parent_id
ORDER BY
    t1.cp_id;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x