我希望使用ActiveRecord获取日期范围中的第一个和最后一个项目。我可以
BalanceLedger.where(created_at: Time.now-7.days..Time.now).order(:created_at).first
和
BalanceLedger.where(created_at: Time.now-7.days..Time.now).order(:created_at).last
获取每周范围内的第一个和最后一个,但是当我只查找2个条目时,这似乎会在每个查询中返回很多。
获得此范围内的第一个和最后一个最有效率是什么?
答案 0 :(得分:1)
您不必运行两个查询。您可以运行一个查询,然后在其上调用 first
和last
。
您可以通过以下方式改进代码,但无论如何都会运行这两个查询。感谢@muistooshort和@jordan在评论中指出这一点。
balance_ledgers = BalanceLedger.where(created_at: Time.now-7.days..Time.now).order(:created_at)
first_one = balance_ledgers.first
last_one = balance_ledgers.last
修改强>
它实际上运行了一个查询,我在Rails控制台中检查了它。见下文:
>> users = User.where(created_at: Time.now-7.days..Time.now).order(:created_at)
User Load (0.5ms) SELECT "users".* FROM "users" WHERE ("users"."created_at" BETWEEN $1 AND $2) ORDER BY "users"."created_at" ASC [["created_at", 2016-11-11 09:59:00 UTC], ["created_at", 2016-11-18 09:59:00 UTC]]
=> #<ActiveRecord::Relation [#<User id: 6, email: nil, first_name: nil, last_name: nil, username: "arslan_ali505", phone_number: nil, address: nil, created_at: "2016-11-14 16:02:27", updated_at: "2016-11-14 16:02:27", role_id: 7, temp_password: "P8ijrXZErI0=", temp_password_changed: false>, #<User id: 7, email: nil, first_name: nil, last_name: nil, username: "arslan_ali_arslan_ali170", phone_number: nil, address: nil, created_at: "2016-11-16 11:41:57", updated_at: "2016-11-16 18:58:37", role_id: 3, temp_password: "e27aad7b817354f3", temp_password_changed: true>, #<User id: 8, email: nil, first_name: "John", last_name: "Don", username: "jhondon213", phone_number: nil, address: nil, created_at: "2016-11-17 13:09:07", updated_at: "2016-11-17 13:09:43", role_id: 7, temp_password: nil, temp_password_changed: true>]>
>> users.first
=> #<User id: 6, email: nil, first_name: nil, last_name: nil, username: "arslan_ali505", phone_number: nil, address: nil, created_at: "2016-11-14 16:02:27", updated_at: "2016-11-14 16:02:27", role_id: 7, temp_password: "P8ijrXZErI0=", temp_password_changed: false>
>> users.last
=> #<User id: 8, email: nil, first_name: "John", last_name: "Don", username: "jhondon213", phone_number: nil, address: nil, created_at: "2016-11-17 13:09:07", updated_at: "2016-11-17 13:09:43", role_id: 7, temp_password: nil, temp_password_changed: true>
击> <击> 撞击>
答案 1 :(得分:-1)
您也可以尝试sql查询&amp;除了使用rails查询之外,它可以直接使用它,它也会改善执行时间。
ActiveRecord::Base.connection.execute("SQL query")