Home >Database >Mysql Tutorial >How to Find the Most Recent Date for Each Model Group in MySQL?

How to Find the Most Recent Date for Each Model Group in MySQL?

Susan Sarandon
Susan SarandonOriginal
2025-01-24 08:31:08581browse

How to Find the Most Recent Date for Each Model Group in MySQL?

Retrieve latest date by model group in MySQL

In database management systems, extracting the latest date associated with each model group is a common task. Let's explore how to implement this in MySQL.

Suppose the following data is stored in a table named "doc":

<code>| NO | model | date     |
+---+-------+----------+
| 1  | bee   | 2011-12-01 |
| 2  | bee   | 2011-12-05 |
| 3  | bee   | 2011-12-12 |
| 4  | tar   | 2011-12-13 |</code>

Our goal is to get a result set showing the latest date for each model:

<code>| model | date     |
+-------+----------+
| bee   | 2011-12-12 |
| tar   | 2011-12-13 |</code>

For this we can use the GROUP BY clause and the MAX() aggregate function:

<code class="language-sql">SELECT model, MAX(date) AS date
FROM doc
GROUP BY model;</code>

This query determines the maximum date for each model in the "doc" table. MAX()The function aggregates the date values ​​in each model group and returns the highest value.

If you intend to retrieve all models with overall maximum date, you can use the following query:

<code class="language-sql">SELECT model, date
FROM doc
WHERE date IN (SELECT MAX(date) FROM doc);</code>

The above is the detailed content of How to Find the Most Recent Date for Each Model Group 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