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
Release: 2025-01-24 08:31:08
Original
579 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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