【问题标题】:Mysql Result 2d array to 1d Ruby on RailsMysql Result 2d array 到 1d Ruby on Rails
【发布时间】:2014-11-06 16:06:41
【问题描述】:

我有一个返回二维数组的查询,但希望它返回一维结果数组。给定:

sql = "SELECT `id` FROM things WHERE other_id = 8" ids = ActiveRecord::Base.connection.execute(sql).to_a

ids 等于

[[1],[2],[3],[4],[5],[9]....]

我正在使用map 创建一个新数组,但它非常慢,有超过 5000 条记录。获取以下格式的最快方法是什么:

[1,2,3,4,5,9...]

【问题讨论】:

  • 为什么需要数组,真的有必要吗?因为如果您只需要 ids 的集合来迭代或构建子查询,那么有更好的方法来做到这一点。只是想提供帮助,即使这有点超出了问题的范围。

标签: ruby-on-rails ruby arrays multidimensional-array


【解决方案1】:

你可以这样做

sql = "SELECT `id` FROM things WHERE other_id = 8"
ids = ActiveRecord::Base.connection.execute(sql).to_a.flatten

更多 Rails 方法是使用#pluck,如下所示:-

Thing.where(other_id: 8).pluck(:id)

【讨论】:

  • @japed 呵呵呵呵.. 寒意:-)
  • 是的,pluck 是去这里的方式。
  • 我不太确定他是否真的定义了模型,但我们很快就会发现._。如果是这种情况,您可能需要添加一些关于如何生成和处理 Rails 模型的参考。
【解决方案2】:

为什么要使用execute 语句?使用ActiveRecord 模型。

Thing.where(other_id: 8).pluck(:id)
# => [1, 2, 3, 4]

【讨论】:

    【解决方案3】:

    假设您的模型和关联设置正确,即

    class Thing < ActiveRecord::Base
      belongs_to :other
    end
    
    class Other < ActiveRecord::Base
      has_many :things
    end
    

    你可以使用ids:

    Thing.where(other_id: 8).ids  #=> [1, 2, 3, 4, 5, 9 ...]
    

    或者,来自Other

    Other.find(8).things.ids      #=> [1, 2, 3, 4, 5, 9 ...]
    

    或:

    Other.find(8).thing_ids       #=> [1, 2, 3, 4, 5, 9 ...]
    

    【讨论】:

    • thing_ids 是最可爱的一个.. :D
    猜你喜欢
    • 2018-08-25
    • 2020-12-11
    • 2022-01-18
    • 2021-05-05
    • 2018-05-31
    • 2021-11-01
    • 1970-01-01
    • 2019-09-20
    • 2021-07-28
    相关资源
    最近更新 更多