如何根据where条件获取MySQL中的前4条记录

时间:2018-01-12 07:21:30

标签: mysql

Sample Data

我在mysql表中有数据,我想从给定的条件中获取最后的记录。 例如:我想通过月份=' 11'和年=' 2017'并获取month_id的11,10,9和8.

我在此处添加了示例数据:http://sqlfiddle.com/#!9/eb01c5/2

谢谢。

5 个答案:

答案 0 :(得分:3)

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

select * from `tablename` where year = 2017 AND month IN (11,10,9,8);

答案 1 :(得分:2)

SQL可以这样编写:

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

如果将年份+月份存储为复合值,则会更简单 - 例如。本月的第一天 - 但同样的逻辑适用于在&#34;之前找到&#34; n记录。

答案 2 :(得分:1)

检查此select * from mt_month where month_id<=11 order by month_id desc limit 4

答案 3 :(得分:1)

由于您知道要从中获取数据的月份,为什么不使用select * from mt_month where start_date BETWEEN '2017-08-01' AND '2017-11-01'来返回数据?相反,感谢传递month_id,您可以传递查询之间的开始日期和结束日期

答案 4 :(得分:1)

您可以执行以下示例:

select * from mt_month
 where year=2017 AND month=11
 order By year Desc limit 4;