代码之家  ›  专栏  ›  技术社区  ›  Henry Yang

如何在Rails类模型范围内使用格式“select…from…where…in(select…)”编写SQL?

  •  0
  • Henry Yang  · 技术社区  · 6 年前

    SELECT * 
    FROM tableA 
    WHERE tableA.col1 IN (
      SELECT tableB.col2 
      FROM tableB
    )
    

    在Rails模型范围内?

    class Book
      def self.select_list_for_current_project_fund_schemes_sponsor_name
        Books.connection.select_all('
          SELECT book.name, book.name 
          FROM BOOK b
          WHERE b.b_pk IN (
            SELECT s.b_fk
            FROM STORE s
          )
        ').rows
      end
    end
    

    它工作,并产生我想要的输出:

    Book.select_list_for_current_project_fund_schemes_sponsor_name
    => [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]
    

    如何在类模型范围内使用ActiveRecord“Where”方法编写上述SQL?

    class Book
      scope :books_in_store_that_exist, -> { where(magic_sql_wrapped_in_ruby_here) }
    
      # more code here...
    end
    

    注:我没有商店模型,我只有书模型。

    Book.books_in_store_that_exist.select(:name).map {|b| [b.name, b.name]}
    => [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Deepak Mahakale    6 年前

    在这种情况下,只需添加一个内部联接

    class Book
      scope :books_in_store_that_exist, -> { joins("INNER JOIN stores ON books.b_pk = stores.b_fk") }
    end
    

    Book.books_in_store_that_exist.select(:name).map { |b| [b.name, b.name] }
    #=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]