Mysql Rails-连接表上查询的索引

Mysql Rails-连接表上查询的索引,mysql,ruby-on-rails,indexing,Mysql,Ruby On Rails,Indexing,在我的应用程序中,文章通过一个自引用的连接模型article\u关系有许多子文章或父文章 class Article < ActiveRecord::Base has_many :parent_child_relationships, :class_name => "ArticleRelationship", :foreign_key => :child_id, :dependent =

在我的应用程序中,文章通过一个自引用的连接模型article\u关系有许多子文章或父文章

class Article < ActiveRecord::Base

  has_many  :parent_child_relationships,
            :class_name   => "ArticleRelationship",
            :foreign_key  => :child_id,
            :dependent    => :destroy
  has_many  :parents,
            :through    => :parent_child_relationships,
            :source     => :parent

  has_many  :child_parent_relationships,
            :class_name   => "ArticleRelationship",
            :foreign_key  => :parent_id,
            :dependent    => :destroy
  has_many  :children,
            :through    => :child_parent_relationships,
            :source     => :child
end

class ArticleRelationship < ActiveRecord::Base
  belongs_to :parent, :class_name => "Article"
  belongs_to :child, :class_name => "Article"
end

有什么方法可以有效地对其进行索引吗?

因此,为了便于阅读

ArticleRelationship.joins(:parent, :child).
 where("((articles.type IN (:parent_article_type) AND parent_id IN (:ids)) OR
         (children_article_relationships.type IN (:child_article_type) AND child_id IN (:ids))
        AND (article_relationships.created_at > :date OR article_relationships.updated_at > :date))",
       { :parent_article_type => "Emotion",
         :child_article_type => "Gateway",
         :ids => [1,2,3,4], :date => "2010-01-01" })
问题在于OR运算符。由于OR,在顶级和表达式中,数据库不能使用索引

  • 由于在创建记录时,它还将updated_at字段设置为相同的时间戳,因此您可以删除或创建的_at,从而在update_at上建立索引
  • 如果可以按项目类型筛选父ID和子ID,则可以删除这些ORs。但是,请确保这样做的效率足够高,不会花太多时间将id列表作为输入进行过滤,并且不会比未编制索引的查询花费更长的时间。首先尝试1.,然后查看索引处更新的_需要多长时间

  • 如果同时执行1和2,请确保使用所有三个字段创建一个索引,即updated_at、parent_id和child_id。

    对于复杂查询,请使用
    squel
    gem。它扩展了你的语法,比如
    不在
    中,
    像任何
    一样,以及其他很酷的功能。值得一试。
    ArticleRelationship.joins(:parent, :child).
     where("((articles.type IN (:parent_article_type) AND parent_id IN (:ids)) OR
             (children_article_relationships.type IN (:child_article_type) AND child_id IN (:ids))
            AND (article_relationships.created_at > :date OR article_relationships.updated_at > :date))",
           { :parent_article_type => "Emotion",
             :child_article_type => "Gateway",
             :ids => [1,2,3,4], :date => "2010-01-01" })