Home > Database > Mysql Tutorial > How to Select the Latest Records for Each Method and ID Combination in MySQL?

How to Select the Latest Records for Each Method and ID Combination in MySQL?

Mary-Kate Olsen
Release: 2024-12-18 18:40:19
Original
215 people have browsed it

How to Select the Latest Records for Each Method and ID Combination in MySQL?

How to Retrieve the Latest Dated Records from a MySQL Table

When storing time-sensitive data in a MySQL table, it's often necessary to retrieve the most recent records for specific combinations of fields. The following example demonstrates how to achieve this when dealing with a table of RPC responses featuring fields such as timestamps, methods, and IDs.

Question

Consider a table named rpc_responses with the following structure:

CREATE TABLE rpc_responses (
  timestamp DATE,
  method VARCHAR,
  id VARCHAR,
  response MEDIUMTEXT,
  PRIMARY KEY (timestamp, method, id)
);
Copy after login

Given the following data:

timestamp method id response
2009-01-10 getThud 16 "....."
2009-01-10 getFoo 12 "....."
2009-01-10 getBar 12 "....."
2009-01-11 getFoo 12 "....."
2009-01-11 getBar 16 "....."

Desired Result

Obtain a list of the most recent responses for all existing combinations of method and id:

timestamp method id response
2009-01-10 getThud 16 "....."
2009-01-10 getBar 12 "....."
2009-01-11 getFoo 12 "....."
2009-01-11 getBar 16 "....."

Answer

To accomplish this, utilize the following query:

SELECT * 
FROM (
    SELECT *,
    IF(@last_method = method, 0, 1) AS new_method_group,
    @last_method := method 
    FROM rpc_responses 
    ORDER BY method, timestamp DESC
) AS t1
WHERE new_method_group = 1;
Copy after login

This query efficiently retrieves the desired result without the need for joins. It also maintains the desired row structure, providing a distinct record for each unique combination of method and id.

The above is the detailed content of How to Select the Latest 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template