Home >Database >Mysql Tutorial >How to Fetch the Latest Row's PID for Each Unique RID in MySQL?

How to Fetch the Latest Row's PID for Each Unique RID in MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 07:12:33202browse

How to Fetch the Latest Row's PID for Each Unique RID in MySQL?

Fetching Latest Row per Group Using MAX() and GROUP BY

Consider a scenario where you have a MySQL table with columns such as timestamp, cost, rid, etc. Your objective is to retrieve the pid of the latest row for each unique rid.

You attempted this using the following query:

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

However, the returned pid values were not aligned with the maximum timestamps. This is because GROUP BY considers all columns in the SELECT clause, and it selects the first matching row for each group.

To rectify this, we need to identify the rid and the maximum timestamp for each group. We can do this using a subquery:

SELECT rid, MAX(timestamp) AS ts
FROM theTable
GROUP BY rid

The result of this query will look like this:

rid | ts
-----|-----
1    | 2011-04-14 01:06:06
2    | 2011-04-14 01:05:41
3    | 2011-04-14 01:14:14

Now, we can join the original table with this subquery, using rid and timestamp, to retrieve the desired pid values:

SELECT theTable.pid, theTable.cost, theTable.timestamp, theTable.rid
FROM theTable
INNER JOIN 
(
    SELECT rid, MAX(timestamp) AS ts
    FROM theTable
    GROUP BY rid
) AS maxt
ON (theTable.rid = maxt.rid AND theTable.timestamp = maxt.ts)

The result of this query will provide you with the pid, cost, timestamp, and rid of the latest row for each unique rid.

The above is the detailed content of How to Fetch the Latest Row's PID for Each Unique RID in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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