日期范围查询MySQL [英] Date Range Query MySQL

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

问题描述

我需要一个查询来选择两个日期之间的数据,以今天的日期为参考。



数据库具有start的datetime字段,datetime字段为end。

  $ todays_date = date(Ymd H:i:s); 

$ q =SELECT * FROM news WHERE`end`> ='。 $ todays_date。 'AND'start`> ='。 $ todays_date。 'ORDER BY id DESC;

问题是查询仍在拉动结果,开始日期大于今天。所以我修改了我的查询看起来像这样:

  $ q =SELECT * FROM news WHERE`end`> = '。 $ todays_date。 'AND'start`> ='。 $ todays_date。 'AND`start`< ='。 $ todays_date。 'ORDER BY id DESC; 

这是使用今天作为限制器的两个datetime字段之间选择数据的正确方法吗? / p>

谢谢

解决方案

您可以使用MySQL中现在的timedate函数 BETWEEN 操作员。



原始SQL:

  SELECT * FROM news 
WHERE NOW()BETWEEN开始和结束

注意:注意默认的时区,这会影响服务器使用的NOW()函数提供您的MySQL资源。


I need a query to select data between two dates with today's date as a reference.

The database has a datetime field for "start" and a datetime field for "end".

$todays_date = date("Y-m-d H:i:s");

$q = "SELECT * FROM news WHERE `end` >= '" .  $todays_date . "' AND `start` >= '" .  $todays_date . "' ORDER BY id DESC";

The problem is the query is still pulling results where the start date is greater than today. So then i modified my query to look like this:

 $q = "SELECT * FROM news WHERE `end` >= '" .  $todays_date . "' AND `start` >= '" .  $todays_date . "' AND `start` <='" . $todays_date . "' ORDER BY id DESC";

Is this the correct way of selection data between two datetime fields that uses todays date as a limiter?

Thanks

解决方案

You can use the now timedate function in MySQL and the BETWEEN operator.

Raw SQL:

SELECT * FROM news
WHERE NOW() BETWEEN start AND end;

Note: Be mindful of the default timezone, which affects the NOW() function, used by the server providing your MySQL resource.

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

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