Home > Database > Mysql Tutorial > How to Efficiently Retrieve the Latest `pid` for Each Unique `rid` Using MySQL's `MAX()` and `GROUP BY`?

How to Efficiently Retrieve the Latest `pid` for Each Unique `rid` Using MySQL's `MAX()` and `GROUP BY`?

Mary-Kate Olsen
Release: 2025-01-01 00:16:09
Original
282 people have browsed it

How to Efficiently Retrieve the Latest `pid` for Each Unique `rid` Using MySQL's `MAX()` and `GROUP BY`?

MySQL Query Optimization: MAX() and GROUP BY

Problem:

Given a table with columns pid, timestamp, cost, and rid, the task is to retrieve the pid of the latest row for each unique rid, considering that pid is auto-increment primary key.

Original Query:

The following query retrieves the maximum timestamp and corresponding rid values, but it doesn't correctly return the latest pid:

SELECT MAX(timestamp), rid, pid FROM theTable GROUP BY rid
Copy after login

Solution:

To effectively get the latest pid for each rid, a combination of techniques is required:

  1. Identify the maximum timestamps and corresponding rid values:

    SELECT rid, MAX(timestamp) AS maxt FROM theTable GROUP BY rid
    Copy after login
  2. Join the original table against the maximum timestamp results:

    SELECT
        t.pid,
        t.cost,
        t.timestamp,
        t.rid
    FROM
        theTable AS t
    JOIN
        (SELECT rid, MAX(timestamp) AS maxt FROM theTable GROUP BY rid) AS maxt
    ON
        t.rid = maxt.rid AND t.timestamp = maxt.maxt
    Copy after login

This revised query effectively retrieves the pid, cost, timestamp, and rid of the latest row for each unique rid in the original table.

The above is the detailed content of How to Efficiently Retrieve the Latest `pid` for Each Unique `rid` Using MySQL's `MAX()` and `GROUP BY`?. 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