Home > Database > Mysql Tutorial > How to Find the Most Recent Records for Each Method and ID Combination in MySQL?

How to Find the Most Recent Records for Each Method and ID Combination in MySQL?

DDD
Release: 2025-01-03 07:16:38
Original
737 people have browsed it

How to Find the Most Recent Records for Each Method and ID Combination in MySQL?

How to Select the Most Recent Records for Combinations of Fields in a MySQL Table

The provided MySQL table, rpc_responses, stores responses to RPC calls with fields including timestamp, method, id, and response. The goal is to retrieve the most recent responses for distinct combinations of method and id.

To achieve this, we can leverage MySQL's ROW_NUMBER() function with a windowing clause:

SELECT *
FROM (
    SELECT *, 
            ROW_NUMBER() OVER (PARTITION BY method, id ORDER BY timestamp DESC) AS row_num
    FROM rpc_responses
) AS subquery
WHERE row_num = 1
Copy after login

This query uses a subquery to calculate the row number for each distinct combination of method and id, ordered in descending order by the timestamp field. The outer query then filters the results to select only the rows with row number 1, which represents the most recent record for each combination.

This approach should efficiently retrieve the desired data without the need for complex joins or temporary tables.

The above is the detailed content of How to Find the Most Recent Records for Each Method and ID Combination in MySQL?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template