【问题标题】:IN clause in :conditions in railsIN 子句 in :conditions in rails
【发布时间】:2012-09-25 18:15:06
【问题描述】:

我在 rails 2 工作,我想执行 Query

PunchingInformation.all(
  :select => "users.id, login, firstname, lastname, 
    sec_to_time(avg(time_to_sec(punching_informations.punch_in_time))) as 'avg_pit',
    sec_to_time(avg(time_to_sec(punching_informations.punch_out_time))) as 'avg_pot'",
  :joins => :user,
  :group => "users.id",
  :conditions => { 
    "punching_informations.date between '#{start_date}' and '#{end_date}'", 
    ["punching_informations.user_id IN (?)", employees.map { |v| v.to_i } ]
  }
)

但它总是返回类似

的错误

Mysql::Error: Unknown column 'punching_informations.date between '2012-09-01' and '2012-09-25'' in 'where clause': SELECT users.id,login, firstname,lastname, sec_to_time( avg(time_to_sec(punching_informations.punch_in_time))) 作为'avg_pit', sec_to_time(avg(time_to_sec(punching_informations.punch_out_time))) as 'avg_pot' FROM punching_informations INNER JOIN users ON users.id = punching_informations.user_id AND (users.type = '用户或 users.type = 'AnonymousUser' ) WHERE (punching_informations.date between '2012-09-01' and '2012-09-25' IN ('punching_informations.user_id IN (?)','--- \n- 28\n- 90\n') ) GROUP BY users.id

需要你的帮助。

【问题讨论】:

  • 你的punching_informations 表中有date 列吗?
  • punching_informations.date between '2012-09-01' and '2012-09-25' IN ... 绝对是错误的 SQL。似乎条件定义不正确。
  • 您的条件实际上并不是一个哈希,虽然是在 {} 中。您是从实际项目中复制的,还是手动编辑的?

标签: ruby-on-rails ruby


【解决方案1】:

有点不清楚你的意思(你有数组,但是像哈希一样用花括号 {}),但似乎 ruby​​ 将第一个字符串 ("punching_informations.date between '#{start_date}' and '#{end_date}'") 视为一列,将第二个数组视为数组的期望值,从而使 IN 条件无效。

如果改写成这样可能会起作用

:conditions => { 
   [ "(punching_informations.date between '#{start_date}' AND '#{end_date}') AND punching_informations.user_id IN (?)", employees.map { |v| v.to_i } ]
 }

甚至更好

:conditions => { 
   [ "(punching_informations.date between ? AND ?) AND punching_informations.user_id IN (?)", start_date, end_date, employees.map { |v| v.to_i } ]
 }

【讨论】:

    【解决方案2】:

    在选择中添加打孔信息.date 和打孔信息.user_id

    :select => "punching_informations.date, punching_informations.user_id, users.id, ....

    【讨论】:

    • 如果你提供一些代码,这个答案会更有帮助,也更容易掌握。
    猜你喜欢
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2012-01-26
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多