MySQL | How to select only one record of each category?

11,027

Solution 1

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT Category, MAX(date) max_date
            FROM    tableName
            GROUP BY Category
        ) b ON a.category = b.category AND
                a.date = b.max_date

for better performance, add a compund INDEX on column Category, date

OR

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT Category, MAX(ID) max_ID
            FROM    tableName
            GROUP BY Category
        ) b ON a.category = b.category AND
                a.ID = b.max_ID

Solution 2

You can use a WHERE clause to filter the data:

select *
from yourtable t1
where (category, date) in (select category, max(date)
                           from yourtable t2
                           group by category)

See SQL Fiddle with Demo

Share:
11,027
KodeFor.Me
Author by

KodeFor.Me

By using the most recent technologies, striving to produce reliable, modern and easy to use applications for end users. After introducing me to the list of CodePoet WordPress consultants, I have devoted almost entirely in development of themes and plugins, while studying techniques and technologies that improve the user experience, such as speed optimization and responsive design. In now days, I have become a Full Stack Developer both for WordPress, Synfomy and Vue.Js, I am capable of design and build Rest APIs, as well to consume and integrate third party Rest APIs to applications need to be connected with the external world

Updated on June 24, 2022

Comments

  • KodeFor.Me
    KodeFor.Me almost 2 years

    I have a table that contains records with data, and each record belongs to a category. Lets say I have the table that following:

    ID | Category | Title    | Date
    --------------------------------------
    1  | Cat 1    | Ttl 1    | 2013-02-18
    2  | Cat 2    | Ttl 2    | 2013-02-18
    3  | Cat 1    | Ttl 3    | 2013-02-20
    

    What I like to do, is to get only one article by each category, and the one I will get must be the latest one in the table.

    In more depth, the result must looks like that:

    ID | Category | Title    | Date
    --------------------------------------
    2  | Cat 2    | Ttl 2    | 2013-02-18
    3  | Cat 1    | Ttl 3    | 2013-02-20
    

    As you can see I have only one record by each category (one for Cat 1 and one for Cat 2) and among the records of the Cat 1 I have the latest.

    How can be translated that in MySQL query ?