如何进行MySQL查询以返回“联接关联”属性/列上的有序记录?

时间:2019-02-24 00:40:34

标签: mysql sql ruby-on-rails activerecord sql-order-by

我的模型大致如下:

class Article < ApplicationRecord
  has_many :writing_associations
  has_many :comments, :through => :writing_associations

  has_many :author_article_associations
  has_many :authors, :through => author_article_associations
end

class Comment < ApplicationRecord
  has_many :writing_associations
  has_many :articles, :through => :writing_associations

  has_many :author_comment_associations
  has_many :authors, :through => :author_comment_associations

  def self.articles_associable_by_author(author)
    author.articles
  end
end

class Author < ApplicationRecord
  has_many :author_article_associations
  has_many :articles, :through => author_article_associations

  has_many :author_comment_associations
  has_many :comments, :through => author_comment_associations
end

class WritingAssociation < ApplicationRecord
  belongs_to :author
  belongs_to :article
  belongs_to :comment
end

class AuthorArticleAssociation < ApplicationRecord
  belongs_to :author
  belongs_to :article
end

class AuthorCommentAssociation < ApplicationRecord
  belongs_to :author
  belongs_to :comment
end

给出一个@comment (以及一个@author等于id的{​​{1}}),我想获得666articlesauthor的{​​{1}}上由created_at排序的writing_associations关联。

我尝试了以下(以及许多其他尝试)而没有成功:

author

以上返回与@comment .articles_associable_by_author(@author) .left_outer_joins(:writing_associations) .order('writing_associations.created_at DESC') .distinct 相关联的articles,这些authorcreated_at [1]上未被writing_associations排序。相关的SQL查询为:

SELECT 
 DISTINCT 
  `articles`.* 
FROM 
 `articles` 
INNER JOIN 
 `author_article_associations` 
 ON `articles`.`id` = `author_article_associations`.`article_id` 
LEFT OUTER JOIN `writing_associations` 
 ON `writing_associations`.`article_id` = `articles`.`id` 
WHERE `author_article_associations`.`creator_user_id` = 666 
ORDER BY writing_associations.created_at DESC

如何进行查询以返回已排序的记录?


[1]此外,左外部联接不关心writing_associations是否与author相关联。我认为JOINS应该运行类似... LEFT OUTER JOIN 'writing_associations' ON 'writing_associations'.'article_id' = 'articles'.'id' AND 'writing_associations'.'author_id' = 666 ...的东西。

0 个答案:

没有答案