【问题标题】:Sorting rows in postgres based on joined table - Rails基于连接表对postgres中的行进行排序 - Rails
【发布时间】:2021-01-09 20:21:51
【问题描述】:

我有以下情况

class Book
  has_many :book_publications
  has_many :publications, through: :book_publications
end

class BookPublication
  # book_id
  # publication_id
end

class Publication
  # date
end

Book1 | Publication1(2000)
Book1 | Publication2(2003)
Book2 | Publication3(2004)
Book2 | Publication4(1999)

我想根据首次出版日期对书籍进行排序,而不关心其他日期。 因此,对于升序,我将有 Book2(1999)、Book1(2000) 和降序 Book1(2000)、Book2(1999)。以后的年份不应计入此查询。 基本上我需要为每本书找到出版的第一年,以某种方式将其附加到查询中并按此排序。 我还需要仍然能够展示没有出版物的书籍。所以我不能只得到匹配的行。

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord


    【解决方案1】:
    class Book
      has_many :book_publications
      has_many :publications, through: :book_publications
      def self.order_by_publication_date
        left_joins(:publications)
          .group(:id)
          .order(Publication.arel_table[:date].minimum, :asc)
      end
    end
    

    如果您想要结果集中的日期,您可以选择它:

    class Book < ApplicationRecord
      has_many :book_publications
      has_many :publications, through: :book_publications
    
      def self.order_by_publication_date
        left_joins(:publications)
          .select(
            arel_table[Arel.star],
            Publication.arel_table[:date].minimum.as('publication_date')
          )
          .group(:id)
          .order(:publication_date, :asc)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      相关资源
      最近更新 更多