Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch previous 4 records in MySQL based on where condition

Tags:

mysql

Sample Data

I have data in mysql table, i want to fetch last records from given condition. example: i want to pass month = '11' and year = '2017' and fetch month_id's 11, 10, 9 and 8.

I have added sample data here: http://sqlfiddle.com/#!9/eb01c5/2

Thank you.

like image 694
harish_sng Avatar asked Jan 28 '23 21:01

harish_sng


2 Answers

select * from `tablename` where year = 2017 AND month<=11 order by month desc  limit 4;

or

select * from `tablename` where year = 2017 AND month IN (11,10,9,8);
like image 181
Niki Avatar answered Feb 03 '23 08:02

Niki


The SQL could be written something like so:

select *
from d
-- find all rows for this month or previous
where
   (year = 2017) and (month <= 11)  -- same month / earlier in same year
or (year < 2017)                    -- earlier year
-- for all found rows, order descending by year, then month
order by year desc, date desc
-- take the first 4 (descending by date)
limit 4

It would be simpler if the year+month were stored as a compound value - eg. the first of the month - but the same logic would apply to find the "n records before".

like image 29
user2864740 Avatar answered Feb 03 '23 06:02

user2864740