替代为NOT IN给出一个空白数组

时间:2011-03-22 12:06:06

标签: mysql ruby-on-rails

我的rails应用程序中有一个查询,

      user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id,     Department.unapproved_departments ).all(:include => [:name, :project]).

这里unapproved_departments在Department表中包含一组id。

当unapproved_departments是一个空白数组时会出现问题。在这些情况下“NOT IN” 检查数组中存在的id,并将整个user_info作为空数组返回。 所以我想拥有除了未经批准的数组之外的所有数据,或者您可以为 NOT IN

提供替代方案。

感谢名单

4 个答案:

答案 0 :(得分:2)

对于NOT IN没有任何问题 - 只是当你没有任何东西时你不想让它发射。

我建议:

  user_info = Information.where("user_id = ?", user)

  unapproved_departments = Department.unapproved_departments
  if unapproved_departments.present?   # true if not blank or nil
    user_info = user_info.where("department_id NOT IN (?)", unaproved_departments) 
  end
  user_info.all(:include => [:name, :project])

如您所见,您可以将条件链接在一起。

答案 1 :(得分:0)

当unapproved_departments为空时,你不能只有一个特例吗?

if Department.unapproved_departments.empty?
    user_info = Information.where("user_id = ?",user.id).all(:include => [:name, :project])
else
     user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id,     Department.unapproved_departments ).all(:include => [:name, :project])
end

答案 2 :(得分:0)

如果你定义更好的未经批准的部门来返回[nil]而不是[]

会更好

否则您可以在代码中添加[0]:

    user_info = Information.where("user_id = ? and department_id NOT IN (?)",user.id,     (Department.unapproved_departments << 0) ).all(:include => [:name, :project]).

答案 3 :(得分:0)

如果我们只关注“NOT IN”部分:

user_info = Information.where("department_id NOT IN (?)", []).to_sql
# => SELECT `informations`.* from `informations` where department_id not in (NULL)

由于空测试,这很奇怪:http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

我们可以做的是扭转测试并获得所需的结果:

user_info = Information.where("NOT (department_id IN (?))", []).to_sql
# => SELECT `informations`.* from `informations` where NOT (department_id in (NULL))

它有效,因为在MySQL中,一切都是!= NULL(同时也是&lt; NULL和&gt; NULL!)。