Home > Database > Mysql Tutorial > How to Retrieve Corresponding Column Values with the Maximum Value in Each Category?

How to Retrieve Corresponding Column Values with the Maximum Value in Each Category?

Mary-Kate Olsen
Release: 2024-12-31 19:59:10
Original
296 people have browsed it

How to Retrieve Corresponding Column Values with the Maximum Value in Each Category?

Retrieving Corresponding Column Values for Maximum Value Query

You're attempting to execute a query that retrieves the maximum video_id value for each video_category and the corresponding column values. However, you're encountering an issue where the query returns the first row instead of the row associated with the maximum video_id.

To address this challenge, an alternative solution is to utilize a subquery to identify the distinct maximum video_id for each video_category. By joining the original table with the subquery, you can effectively link each maximum video_id to its corresponding column values:

SELECT
   s.video_id
   ,s.video_category
   ,s.video_url
   ,s.video_date
   ,s.video_title
   ,s.short_description
FROM videos s
   JOIN (SELECT MAX(video_id) AS id FROM videos GROUP BY video_category) max
      ON s.video_id = max.id
Copy after login

This revised query employs an INNER JOIN, which preserves only the rows that satisfy the join condition. In this case, the join ensures that the rows in the main table (s) are matched to the rows in the subquery (max) based on the video_id equivalence.

By leveraging this approach, you can retrieve the maximum video_id for each category and the corresponding values for video_url, video_date, video_title, and short_description.

The above is the detailed content of How to Retrieve Corresponding Column Values with the Maximum Value in Each Category?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template