本文介绍了使用Rails,MySQL和Active Record查询date = Date.today的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Active Record文档中看到,您可以使用大于/小于比较来查询日期。但是,如果要选择date = Date.today,或者我必须查询大于昨天而小于明天的日期该怎么办?

I see in the Active Record docs, you can query for a date using a greater than / less than comparison. However, what if you want to select where date = Date.today or must I query where date is greater than yesterday and less than tomorrow?

正如您所看到的,我在以下查询中确实这样做,并且查询Date =今天返回空集的地方

As you can see, I'm doing exactly that in the following queries and querying where Date = today returns an empty set

1.9.3p286 :096 > Subscription.where("created_at = ?", Date.today).count
   (0.5ms)  SELECT COUNT(*) FROM `subscriptions` WHERE (created_at = '2013-01-18')
 => 0

vs。

1.9.3p286 :098 > Subscription.where("expiration_date < ? AND expiration_date > ?", Date.today + 1, Date.today - 1).count
   (0.4ms)  SELECT COUNT(*) FROM `subscriptions` WHERE (expiration_date < '2013-01-19' AND expiration_date > '2013-01-17')
 => 1

这是查询今天日期的正确方法还是我遗漏了什么?

Is this the proper way to query for today's date or am I missing something?

推荐答案

我认为这是此问题的DUP:

I think this is a DUP of this question:

Subscription.where("DATE(created_at) = ?", Date.today).count

我很确定这可以在MySQL和PostgreSQL中使用,但是我不确定这是否是SQL标准。

I'm pretty sure this works in MySQL and PostgreSQL, but I'm not sure if it's a SQL standard.

维基百科似乎认为 TO_DATE 将是标准:

Wikipedia seems to think TO_DATE would be the standard:http://en.wikipedia.org/wiki/SQL#Date_and_time

这在PostgreSQL中对我不起作用。

That didn't work for me in PostgreSQL though.

这篇关于使用Rails,MySQL和Active Record查询date = Date.today的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:12