【问题标题】:rails way to fetch records from same table with different typesrails方法从不同类型的同一张表中获取记录
【发布时间】:2015-02-23 10:32:06
【问题描述】:

我想从同一张表 Ticket 中获取三种类型的门票。像这样

Ticket.where(type: 'a').limit(5)
Ticket.where(type: 'b').limit(5)
Ticket.where(type: 'c').limit(5)

在 Rails 中,以最少的数据库命中率获取与上述三个查询等效的数据的最佳方法是什么。

【问题讨论】:

  • 我想要 15 条记录,包括“a”、“b”和“c”每种类型的 5 条记录。

标签: sql database ruby-on-rails-4 activerecord relational-database


【解决方案1】:

您可以使用IN

types = [a,b,c]

Ticket.where("type IN (?)", types).limit(5)

【讨论】:

  • 它将给我们 5 条记录,但我们需要每种类型的 5 条记录。总共 15 个。
  • @AdnanAli 有趣。完全错过了这一点。将继续关注这一点。
【解决方案2】:

我认为你需要使用 sql UNION 查询。你可以看到这个答案: ActiveRecord Query Union

或者只使用 rails 的总和来制作所有这些东西。这不是优雅的解决方案,但您可以尝试:

scope :by_type, ->(type){ where(type: type).limit(5) }

def self.foo
  Ticket.by_type('a') + Ticket.by_type('b') + Ticket.by_type('c')
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多