【问题标题】:ActiveRecord query with between dates and has first attribute value日期之间的 ActiveRecord 查询并具有第一个属性值
【发布时间】:2014-05-16 18:59:53
【问题描述】:

Ruby on Rails 3.2

步骤

1) 获取每个用户

2) 如果有相同 reseller_id 值的用户,只取第一个用户。

3) 在日期之间获取用户

4) 计数

例子:

h=User.all.select(:reseller_id).first
h.where(created_at: '2014-01-01'..'2014-03-31')
h.count

注意

我需要检查所有 User 是否是第一个使用 reseller_id 的。然后检查日期之间。

【问题讨论】:

  • 你的意思是这样吗? User.where(created_at: '2014-01-01'..'2014-03-31').first
  • @anonymousxxx 不,那只会给出第一条记录。日期之间将有数百个
  • User.select(:reseller_id).where(created_at: '2014-01-01'..'2014-03-31').uniq ?
  • @Pavan 这返回了 nil。 ://
  • @anonymousxxx 你的效果很好。它返回每个用户的 reseller_id。我只是分配它并计数。请张贴作为答案。如果你能先让它不是唯一的

标签: mysql ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

你错过了几件事。你需要看看那个where生成的sql。

> User.where(created_at: '2014-01-01'..'2014-03-31').to_sql
 => "SELECT `users`.* FROM `users`  WHERE (`users`.`created_at` BETWEEN '2014-01-01' AND '2014-03-31')"

所以,你想要的是

User.where(created_at: '2014-01-01'..'2014-03-31', reseller_id: <somevalue>).first

也许您还想要一个订单?那可以加在.first之前

我正在根据下面的 cmets更新这个答案。

首先,您获得所需的 reseller_id:

reseller_id = User.where(created_at: '2014-01-01'..'2014-03-31').where("reseller_id is not null").select(:reseller_id).first

然后,运行第二个查询:

users = User.where(created_at: '2014-01-01'..'2014-04-01', reseller_id: reseller_id)

你应该是金色的。

【讨论】:

  • 但 reseller_id 值可以是任何值。我想要任何 reseller_id 的第一个用户
  • User.where(created_at: '2014-01-01'..'2014-03-31', fullname: 'evan').where("reseller_id IS NOT NULL").first 您可以使用活动记录和原始 sql 将 where 子句串在一起。
  • .first 将只返回第一条记录。我想要除第一个具有 reseller_id 的用户之外的所有记录
  • 啊!只需将其作为两个查询来执行? first_id = User.where(created_at: '2014-01-01'..'2014-03-31').where("reseller_id is not null").pluck(:reseller_id); User.where(created_at: '2014-01-01'..'2014-03-31', reseller_id: first_id)
  • 似乎有效,只是奇怪的是它给出的结果与 User.select(:reseller_id).where(created_at: '2014-01-01'..'2014-03-31') 相同。独特的
【解决方案2】:

遍历所有用户记录并仅获取具有相同属性值的第一条记录...

这只会在用户的某个字段中为每个唯一值获取一条记录(此处的某些字段为reseller_id

h=User.select('DISTINCT reseller_id')

这会在日期之间获取我想要的记录。

t=h.where(created_at: '2014-01-01'..'2014-04-01')

然后数一数。

t.count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    相关资源
    最近更新 更多