What query will produce rows from 2 highest dates?

Discussion in 'MySQL' started by KingCobra, Aug 10, 2010.

  1. #1
    Here is my 'news' table with the field 'news_date'.

    news_date
    -----------
    2009-12-11
    2009-12-31
    2009-12-31
    2010-01-01
    2010-01-01
    2010-02-01
    2010-02-01
    2010-02-01
    2010-02-01
    2010-02-03
    2010-02-03
    2010-02-03

    What will be the query that produce max 2 dates (all rows form max date & two rows from second max date) rows like bellow-

    (ASC order)
    2010-02-01
    2010-02-01
    2010-02-03
    2010-02-03
    2010-02-03

    (DESC order)
    2010-02-03
    2010-02-03
    2010-02-03
    2010-02-01
    2010-02-01

    PLEASE HELP ME
     
    Last edited: Aug 10, 2010
    KingCobra, Aug 10, 2010 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You probably need a subquery. Something like:

    SELECT news_date FROM my_table WHERE news_date IN (SELECT news_date FROM my_table GROUP BY news_date ORDER BY news_date DESC LIMIT 2);

    There may be another way to do it, but off the top of my head this should work. If you want ASC, just change it in the subquery. ALso, make sure you have an index on news_date to speed this up.
     
    jestep, Aug 10, 2010 IP
  3. mysql guru

    mysql guru Peon

    Messages:
    15
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    0
    #3
    SELECT * FROM tt where t1=(select max(t1) from tt) -- all rows from max date
    union all
    ( SELECT * FROM tt where t1=(select max(t1) from tt where t1<(select max(t1) from tt)) limit 2) -- 2 rows from second max date
     
    mysql guru, Aug 12, 2010 IP