【问题标题】:How to achieve optimized mysql query in ruby on rails?如何在 ruby​​ on rails 中实现优化的 mysql 查询?
【发布时间】:2020-02-24 08:49:55
【问题描述】:

模型结构: Comment 模型有 belongs_to 关系 和Resource 模型没有任何关系。

class Comment < ApplicationRecord
 belongs_to :resource

end
Class Resource < ApplicationRecord

#No relation

end

这是我的查询: (希望这不是我使用的 n+1 包含)

comments = Comment.where(id: [5,6,7]).includes(:resource)
Hash[comments.map { |comment|
                          [comment.id, comment.resource] if comment.resource 
                      }]

我得到的输出是这样的: 其中5和6是comment_id,其他是resource _attributes

 5=>
  #<Resource:0x00007fa9b2a93518
   id: 3,
   url: "http://url.com",
   description: "og:description",
   title: "title",
   site_name: "og:site_name",
   image_url: "http://imageurl.com",
   video_url: nil,
   created_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
   updated_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
   embed_html: nil,
   url_hash: "df5ac6d4a1313ecb9949312d0258416a248333f68ae39aa1c7acd818e7d997e7",
   user_id: nil>,
 6=>
  #<Resource:0x00007fa9b2a92fa0
   id: 4,
   url: "http://url.com",
   description: "og:description",
   title: "title",
   site_name: "og:site_name",
   image_url: "http://imageurl.com",
   video_url: nil,
   created_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
   updated_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
   embed_html: nil,
   url_hash: "df5ac6d4a1313ecb9949312d0258416a248333f68ae39aa1c7acd818e7d997e7",
   user_id: nil>}

但我需要更优化的查询和输出应该是这样的:

5=>
  #<Resource:0x00007fa9b2a93518
   id: 3,
   url: "http://url.com",
   description: "og:description",
,
 6=>
  #<Resource:0x00007fa9b2a92fa0
   id: 4,
   url: "http://url.com",
   description: "og:description"
}

【问题讨论】:

    标签: mysql ruby-on-rails ruby optimization


    【解决方案1】:

    您可以使用 INNER JOIN 代替 Rails 包含并且根本不实例化 Resource 对象。

    data = Comment.where(id: [5, 6, 7])
                  .joins(:resource)
                  .select(
                    'comments.id AS comment_id',
                    'resources.id AS r_id',
                    'resources.url AS r_url',
                    'resources.description AS r_desc'
                  )
    hash = Hash[data.map { |e| [e.comment_id, { id: e.r_id, url: e.r_url, desc: e.r_desc }] }]
    

    它应该给你这样的结果:

    {
      5 => { id: 3, url: "http://url.com", desc: "og:description" },
      6 => { id: 4, url: "http://url.com", description: "og:description" }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多