【问题标题】:Two arrays to be evaluated element by element in query查询中要逐个元素评估的两个数组
【发布时间】:2013-12-25 02:00:45
【问题描述】:

抱歉标题不清楚,但我希望正文能清楚地描述我的问题。

所以我有两个数组

title_id: [1542, 1507, 47, 1436, 1527, 3, 173, 1534, 1876, 398]
ref_no: [10, 10, 74, 12, 9, 35, 10, 9, 1, 42]

我想查询使得第一个数组的索引应该与第二个数组的索引为 AND。 就像:title_id = 1542,我只想用 ref_no = 10 来与它。等等。

我尝试了以下查询,但它就像乘以 indecies:

Book.where("title_id IN (?) AND ref_no IN (?) ", @ids.map(&:title_id), @ids.map(&:ref_no))

使用:RoR 3,PGSQL

【问题讨论】:

  • 你想要(title_id = 1542 and ref_no = 10) or (title_id = 1507 and ref_no = 10) or (title_id = 47 and ref_no = 74) or ...
  • 是的,这就是我想要的

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


【解决方案1】:

这种事情在 PostgreSQL 的 SQL 风格中非常容易。您可以像这样加入 VALUES 表达式:

select books.*
from books b
join (values (1542, 10), (1507, 10), ...) as dt(t, r)
     on b.title_id = dt.t and b.ref_no = dt.r

或者您可以使用 ANY 和数组或 IN:

where (title_id, ref_no) = any (array[(1542,10), (1507, 10), ...])

where (title_id, ref_no) in ((1542,10), (1507, 10), ...)

或通常的 OR 大混乱:

where (title_id = 1542 and ref_no = 10)
   or (title_id = 1507 and ref_no = 10)
   or ...

第二个选项(IN变体):

where (title_id, ref_no) in ((1542,10), (1507, 10), ...)

最符合您的 IMO 意图。我想不出任何愉快的方式来让 AR 构建它,但是,由于我们正在处理整数并且不必担心引用和转义问题,我们可以通过一些字符串争论来做到这一点:

trs = @ids.map { |o| "(#{o.title_id.to_i}, #{o.ref_no.to_i})" }.join(',')
Book.where("(title_id, ref_no) in (#{trs})")

您可能可以使用一些长链难以理解的 AREL 调用来构建 OR 版本,但当事情变得比 AR 想要说的婴儿谈话a = b and c = d SQL 更复杂时,我倾向于放弃 AR 并直接使用 SQL .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    相关资源
    最近更新 更多