【问题标题】:SQL - Rails query between opening and closing time of storeSQL - 商店开闭时间之间的 Rails 查询
【发布时间】:2018-03-20 06:51:45
【问题描述】:

我使用 postgresql 作为我的数据库。 目前我有计时模型,其中包含open_atclose_at 字段。两个字段的数据类型都是时间。

2.4.2 :077 > Time.current
 => Tue, 20 Mar 2018 06:46:28 UTC +00:00 

=> #<Timing id: 3, day: "Tuesday", open_at: "2000-01-01 04:00:00", close_at: "2000-01-01 01:00:00", warehouse_id: 9, created_at: "2018-03-19 10:45:36", updated_at: "2018-03-20 06:34:16"> 

以上计时记录的开放时间为凌晨4点,关闭时间为凌晨1点。当前时间是 6 点 46 分。所以当我做下面的查询时

2.4.2 :079 > Timing.where("open_at < ? and close_at > ?", Time.current, Time.current)
  Timing Load (0.7ms)  SELECT  "timings".* FROM "timings" WHERE (open_at < '2018-03-20 06:48:09.004429' and close_at > '2018-03-20 06:48:09.004496') LIMIT $1  [["LIMIT", 11]]
 => #<ActiveRecord::Relation []> 

它应该是结果,但结果是空的,但是当我将关闭时间更改为晚上 11 点时,意味着 23:00:00。并在查询下方运行

Timing.where("open_at < ? and close_at > ?", Time.current, Time.current)
  Timing Load (0.8ms)  SELECT  "timings".* FROM "timings" WHERE (open_at < '2018-03-20 06:49:12.307156' and close_at > '2018-03-20 06:49:12.307205') LIMIT $1  [["LIMIT", 11]]
 => #<ActiveRecord::Relation [#<Timing id: 3, day: "Tuesday", open_at: "2000-01-01 04:00:00", close_at: "2000-01-01 23:59:00", warehouse_id: 9, created_at: "2018-03-19 10:45:36", updated_at: "2018-03-20 06:49:07">]> 

结果来了。谁能解释时间有什么问题?或者如果我想获得正确的记录应该如何查询

**

更新 - 在 schema.rb 中添加时序表

**

schema.rb

  create_table "timings", force: :cascade do |t|
    t.string "day"
    t.time "open_at"
    t.time "close_at"
    t.bigint "warehouse_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["warehouse_id"], name: "index_timings_on_warehouse_id"
  end

【问题讨论】:

  • 可能问题出在时间格式上。如果我没记错数据库总是以 24 小时格式存储时间,所以你的关闭时间小于打开时间(在第一种情况下)。
  • @kunashir 是的,你是对的。但是如何解决这个问题?
  • 使用time 格式而不是datetime postgresql.org/docs/9.1/static/datatype-datetime.html
  • @meta 当前字段的数据类型是时间。并且只检查当前时间。所以可能不是问题
  • 不,这显然是datetime(PQ 术语中的timestamp)格式:“2000-01-01 04:00:00”,您需要的是time,它看起来像这个“04:00:00”

标签: ruby-on-rails postgresql ruby-on-rails-5


【解决方案1】:

如果你的问题是时间格式,可以使用next:

Time.now.strftime("%I:%M %p") #=> It returns current time in AM/PM format
Time.strptime( '1:00 PM', '%I:%M %p') #=> return time in 24 hours format
=> 2018-03-20 13:00:00 +0300 

并用它来向 DB 发出请求。

【讨论】:

  • 感谢您的回答。但目前它也采用 24 小时格式。因为我可以以 24 小时格式存储时间,Time.current 也返回 24 小时格式。我需要询问它是如何工作的
  • close_at: "2000-01-01 01:00:00" - 我认为这是不正确的(晚上 1 小时)。我建议您从前端获取 AM/PM 格式的时间,如果是,您需要手动将其转换为 24 小时格式。
  • 是的,close_at: "2000-01-01 01:00:00"是 1 小时的夜晚。就我而言,商店的营业时间是上午 8 点,关门时间是凌晨 1 点。你明白我的意思吗?如果我在下午 1 点关闭商店,而不是将关闭时间存储为 close_at: "2000-01-01 13:00:00"
  • postgres 足够聪明,可以理解 AM/PM 格式。比如Timing.where('open_at::time &gt; ? AND close_at::time &lt; ?', '07:00:00 AM', '01:00:00 AM')也是正确的但是不会返回任何数据
  • 哦..我明白了。有趣的案例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多