2014-11-05 41 views
0

我一个JSON API的使用,以及输入参数之一是指定这样定义的整数输入:查询返回的结果,其中日期时间是在X月

1 - would return results within one month from today 
2 - would return results within three months from today 
3 - would return results within six months from today 
4 - would return results within one year from today 

所以在本质上是API将如下使用:

http://url.com/index.php?route=api/order/all&search_time=1,将从今天起在一个月内返回表X的所有结果。

我的表格有datetime字段,所以日期问题不是问题。我知道在哪里可以检索到像MONTH(datetime_item)这样的月份的MySQL函数,因此您可以像WHERE MONTH(datetime_item) = 8那样使用它,但这与我的用法无关。

所以在MySQL的伪代码,查询应该是这样的:

WHERE datetime is within three months ago from today

+0

检查:http://www.w3schools.com/sql/func_datediff_mysql.asp – vaso123 2014-11-05 09:12:32

+0

@lolka_bolka不知道SO鼓励,作为一个资源(http://meta.stackexchange.com/questions/87678/discouraging -w3schools-as-a-resource) – Strawberry 2014-11-05 09:16:56

回答

1

试试这个,

SELECT * from table_name where datetime_item >= now()-interval 'x' month 

日期算术也可以使用间隔连同执行+或 - 运营商:

date + INTERVAL expr unit 
date - INTERVAL expr unit 

Reference - documentation for date/time functionsDocumentation for date/time functions

+1

这是为什么downvoted? – theGreenCabbage 2014-11-05 09:31:00

+1

这就是我最终使用的。似乎为我工作正常 - 如果有人想澄清为什么这是downvoted ..随意。 – theGreenCabbage 2014-11-05 10:01:11

+1

我认为没有理由downvote,+1 – fancyPants 2014-11-05 10:01:30