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]...]