简体   繁体   English

如何使用MySQL从新闻表中选择最近6个月

[英]How to select last 6 months from news table using MySQL

I am trying to select the last 6 months of entries in a table, I have a column called datetime and this is in a datetime mysql format. 我试图选择一个表中的最后6个月的条目,我有一列称为datetime,这是一种datetime mysql格式。

I have seen many ways using interval and other methods - which method should I use? 我已经看到许多使用间隔和其他方法的方法-应该使用哪种方法? Thanks 谢谢

使用DATE_SUB

 .... where yourdate_column > DATE_SUB(now(), INTERVAL 6 MONTH)

Try this: 尝试这个:

select *
  from table 
 where your_dt_field >= date_sub(now(), interval 6 month);

Query reads: give me all entries in table where the field corresponding to the entry date is newer than 6 months. 查询内容:给我table中的所有条目,其中对应于条目日期的字段比6个月新。

I tried @user319198 answer to display last 6 months (sum of) sales, it worked but I faced one issue in the oldest month, i do not get the sales amount of the whole month. 我尝试使用@ user319198答案来显示最近6个月的销售额(总和),但它有效,但是我在最旧的月份遇到了一个问题,我没有获得整个月的销售额。 The result starts from the equivalent current day of that month. 结果从该月的当前当日开始。

Just I want to share my solution if any one interested:- 如果有人感兴趣,我只想分享我的解决方案:-

yourdate_column > DATE_SUB(now(), INTERVAL 7 MONTH)
limit 6

Also it will be great if anyone has better solution for my case J. 如果有人对我的案例J有更好的解决方案,那也很好。

To me, this looks like a solution as I'm using it with MariaDB, take a look at WHERE clause: 对我来说,这就像是将其与MariaDB一起使用时的解决方案,请看一下WHERE子句:

SELECT MONTH(yourTimestampOrDateColumn) AS MONTH, USER, ActionID, COUNT(*) AS TOTAL_ACTIONS, ROUND(SUM(totalpoints)) AS TOTAL_PTS
FROM MyTable
WHERE MONTH(yourTimestampOrDateColumn) BETWEEN MONTH(CURDATE() - INTERVAL 6 MONTH) AND MONTH(CURDATE())
GROUP BY MONTH;

queryResults

On the image we see only months where user had actual data recorded in a DB (thus showing only 4 months instead of 6). 在图像上,我们仅看到用户在数据库中记录了实际数据的月份(因此,仅显示4个月而不是6个月)。

So this month is 10th (October), 6 months ago was 4th month (April), thus query will look for that interval (from 4 to 10). 因此,本月是10月(10月),而6个月前是4月(4月),因此查询将查找该间隔(从4到10)。

您也可以使用TIMESTAMPDIFF

    TIMESTAMPDIFF(MONTH, your_date_column, now()) <= 6 )

You can get last six month's data by subtracting interval of 6 month from CURDATE() ( CURDATE() is MySQL function which returns Today's date ). 您可以通过从CURDATE()减去6个月的interval of 6 month来获取最近六个月的数据( CURDATE()是MySQL函数,它返回Today的date )。

SELECT * FROM table 
         WHERE your_date_field >= CURDATE() - INTERVAL 6 MONTH;

Or you can use BETWEEN operator of MySQL as Below: 或者您可以使用MySQL的BETWEEN运算符,如下所示:

SELECT * FROM table 
         WHERE your_date_field BETWEEN CURDATE() - INTERVAL 6 MONTH AND CURDATE();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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