已修复 - 这就是我现在所拥有的 - 用ASP编写
If Session("dateRange") = "Today" Then
fromDate = Date()
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated = '"&fromDate&"' "
ElseIf Session("dateRange") = "Yesterday" Then
fromDate = DateAdd("d",-1,Date())
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated = '"&fromDate&"' "
ElseIf Session("dateRange") = "1 Week" Then
fromDate = DateAdd("d",-7,Date())
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated BETWEEN '"&fromDate&"' AND '"&toDate&"' "
ElseIf Session("dateRange") = "1 Month" Then
fromDate = DateAdd("m",-1,Date())
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated BETWEEN '"&fromDate&"' AND '"&toDate&"' "
ElseIf Session("dateRange") = "3 Months" Then
fromDate = DateAdd("m",-3,Date())
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated BETWEEN '"&fromDate&"' AND '"&toDate&"' "
ElseIf Session("dateRange") = "6 Months" Then
fromDate = DateAdd("m",-6,Date())
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated BETWEEN '"&fromDate&"' AND '"&toDate&"' "
ElseIf Session("dateRange") = "1 Year" Then
fromDate = DateAdd("yyyy",-1,Date())
fromDate = Year(fromDate)&"-"&Month(fromDate)&"-"&Day(fromDate)
whereClause = whereClause & "AND dateCreated BETWEEN '"&fromDate&"' AND '"&toDate&"' "
End If
原始问题:
简单的问题,但由于某种原因,我似乎无法使其发挥作用。
我有一个搜索框,旁边是日期范围选择菜单,因此用户可以在最近1个月,6个月或12个月内搜索照片。
我所拥有的不是错误,但它应该没有产生结果,这就是:
WHERE dateCreated BETWEEN "&DateAdd("m",-6,Date())&" AND "&Date()&"
SQL输出产生:
dateCreated BETWEEN 18/03/2011 AND 18/09/2011 ORDER BY dateCreated DESC
数据库'dateCreated'字段设置为(Date INDEX)。
有人能看出出了什么问题吗?
答案 0 :(得分:31)
生成的SQL中的日期应使用单引号引用。尝试使用引号围绕查询的动态部分。像这样:
WHERE dateCreated BETWEEN '"&DateAdd("m",-6,Date())&"' AND '"&Date()&"'
我认为会生成这个SQL:
dateCreated BETWEEN '18/03/2011' AND '18/09/2011' ORDER BY dateCreated DESC
另外,看看您是否可以找到一种格式化日常格式的MySQL yyyy-mm-dd
格式的方法。像这样:
dateCreated BETWEEN '2011-03-18' AND '2011-09-18' ORDER BY dateCreated DESC
答案 1 :(得分:7)
如果您特意向后看“现在”,为什么不这样做
where DateCreated >= DATE_SUB( CURDATE(), INTERVAL 1 MONTH )
where DateCreated >= DATE_SUB( CURDATE(), INTERVAL 6 MONTH )
where DateCreated >= DATE_SUB( CURDATE(), INTERVAL 12 MONTH )
不需要“范围”,只需插入您想要允许的月份范围......
答案 2 :(得分:2)
%d-%m-%Y
不是正确的日期格式,MySQL中的日期值应始终引用相同的字符串和ISO 8601('%Y-%m-%d'
)格式。 18/03/2011
将被解释为18
除以03
和2011
,其中包含0.002…
。
也就是说,您的SQL应该类似于以下形式:
dateCreated BETWEEN '2011-03-18' AND '2011-09-18' ORDER BY dateCreated DESC
答案 3 :(得分:0)
不确定您使用DateAdd()
的技术,但除了您的日期值未用单引号括起来之外,您的最终日期格式也是错误的。
MySQL将日期比较为2011-03-18
而不是18/03/2011
。
请注意,您可以使用Date Time Functions在MySQL中执行此操作。虽然可能阻止查询被缓存。
答案 4 :(得分:0)
如果这些字符串没有引用,我相信你实际上只是在进行分工,然后在非常短的时间范围内比较日期。