Home > Database > Mysql Tutorial > How to Select the 3 Most Recent Distinct Records in SQL?

How to Select the 3 Most Recent Distinct Records in SQL?

Barbara Streisand
Release: 2024-11-28 07:06:11
Original
1048 people have browsed it

How to Select the 3 Most Recent Distinct Records in SQL?

Selecting Distinctly Recent Records with SQL

In this query, the task is to extract the three most recent records from a table while ensuring that the values in a specific column, otheridentifier, are distinct. The following SQL statement was attempted:

SELECT * FROM `table` GROUP BY (`otheridentifier`) ORDER BY `time` DESC LIMIT 3
Copy after login

This query, however, yielded unexpected results due to the precedence of grouping over ordering in SQL. To achieve the desired outcome, a more intricate approach is necessary:

SELECT *
FROM `table`
WHERE `id` = (
    SELECT `id`
    FROM `table` as `alt`
    WHERE `alt`.`otheridentifier` = `table`.`otheridentifier`
    ORDER BY `time` DESC
    LIMIT 1
)
ORDER BY `time` DESC
LIMIT 3
Copy after login

This query consists of a nested select statement that identifies the most recent record for each distinct otheridentifier value. The result is then filtered to ensure that only the three most recent records are retrieved.

The above is the detailed content of How to Select the 3 Most Recent Distinct Records in SQL?. For more information, please follow other related articles on the PHP Chinese website!

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