简体   繁体   中英

How to get latest 3 records of each month of each year?

Is there a single query in mysql to get latest 3 records of each month for each year ? Or it should be done through Loop ?

ie

YEAR 2011

january 

Record 1
Record 2
Record 3

May 

Record 1
Record 2
Record 3

September 

Record 1
Record 2
Record 3

YEAR 2012

August 

Record 1
Record 2
Record 3

Nov 

Record 1
Record 2
Record 3

Dec 

Record 1
Record 2
Record 3

and so on.

A guess that it can be achieved with loop but not sure what's the better way to acheive this.

Try it using some sample application. Remember I did this so you can use naming convention as per your desire.

First created database table as below. I have named this table 'threemonth'


id auto_increament,
title varchar 255,
created date

title is just to sure for non repeating result,

Now create one php file and make database connection and all.

Now copy paste below query inside that page.


SELECT YEAR(created) as stat_year,
       MONTH(created) as stat_month,
       COUNT(*) as stat_count,
       title,
       GROUP_CONCAT(created) as FinalResult,
       id
FROM
      `threemonth`
GROUP BY stat_year,stat_month
ORDER BY created DESC

Above query will out put something like below.


stat_year = 2012
stat_month = 12
stat_count = 2
FinalResult = comma separated date listing becaue of concating result.
title and id  

Now when displaying record, display it as your desire.

Just explode comma separated created field and only display first three record and you are done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM