MySQL选择日期范围问题 [英] MySQL select date range issue

查看:51
本文介绍了MySQL选择日期范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.我在SQL查询中使用BETWEEN得到了一些奇怪的结果,并且想知道是否有人可以帮助我理解为什么我得到了我得到的结果.

Hey guys. I'm getting some strange results from using BETWEEN in my sql query and am wondering if anyone can help me to understand why i am getting the results i'm getting.

我正在搜索dd/mm/yyyy格式的日期范围.所以我想选择某个日期范围内的所有条目.

I'm searching a date range in the format of dd/mm/yyyy. So i want to select all entries within a certain date range.

$dbSearchRecords_result = "SELECT * FROM $tbl_name WHERE Date BETWEEN '$DateFrom_order' AND '$DateTo_order'";

$dbSearchRecords_result = mysql_query($dbSearchRecords_result);

然后我在来自数组的while语句中调用结果

i am then calling the results in a while statement from an array

while ($row = mysql_fetch_array($dbSearchRecords_result)){

现在,如果我搜索2011年12月2日至2011年2月14日之间,则返回的日期为2010年12月13日.

Now if I search BETWEEN 12/02/2011 14/02/2011 there is a date returned from 13/12/2010.

但是,如果我搜索2011年12月2日13/02/201,我没有得到2010年12月13日的结果.

Yet if I search 12/02/2011 13/02/201 I do not get the result of 13/12/2010.

任何想法都会受到赞赏.

Any ideas would be most appreciated.

干杯.

推荐答案

BETWEEN运算符最有可能以字符串形式读取您的范围. 摘自本书:

The BETWEENoperator is most likely reading your ranges as strings. From the book:

使用BETWEEN时可获得最佳效果 日期或时间值,请使用CAST() 将值显式转换为 所需的数据类型.示例:如果 您将一个DATETIME与两个DATE进行比较 值,将DATE值转换为 DATETIME值.如果您使用字符串 常数,例如"2001-1-1" 与DATE比较,强制转换字符串 到DATE.

For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

因此,尝试:

SELECT * FROM `mytable` 
WHERE `date` BETWEEN CAST('2011-01-02' AS DATE) AND CAST('2011-12-02' AS DATE)

这篇关于MySQL选择日期范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆