2014-03-06 69 views
2

我有一張名爲「Books」的has_many「章節」表,我希望獲得所有擁有超過10章的書籍。我如何在單個查詢中執行此操作?Rails SQL查詢計數

我有這個迄今爲止...

Books.joins('LEFT JOIN chapters ON chapters.book_id = books.id') 

回答

0

找到了解決辦法...

query = <<-SQL 
    UPDATE books AS b 
    INNER JOIN 
    (
     SELECT books.id 
     FROM books 
     JOIN chapters ON chapters.book_id = books.id 
     GROUP BY books.id 
     HAVING count(chapters.id) > 10 
) i 
    ON b.id = i.id 
    SET long_book = true; 
SQL 

ActiveRecord::Base.connection.execute(query) 
0

我不知道鐵軌非常好,但SQL會是這樣:

SELECT b.* FROM Books b 
JOIN Chapters c ON b.id = c.book_id 
GROUP BY b.id 
HAVING COUNT(*) > 10 

根據ActiveRecord的文檔它會然後是

Books.joins(:chapters) 
    .group('books.id') 
    .having('count() > 10') 

更新:我想通了。在這裏我所做的在軌如果它可以幫助任何人

query = <<-SQL 
    UPDATE books AS b 
    INNER JOIN 
    (
     SELECT books.id 
     FROM books 
     JOIN chapters ON chapters.book_id = books.id 
     GROUP BY books.id 
     HAVING count(chapters.id) > 10 
) i 
    ON b.id = i.id 
    SET long_book = true; 
SQL 

ActiveRecord::Base.connection.execute(query) 
+0

這不起作用對我而言,因爲我無法對數據做任何事情。它需要選擇或where子句的地方,因爲當我這樣做: Books.joins(:章) 。集團( 'books.id') .having( '計數()> 10') .update_all( long_book:true) 它更新所有的書籍,而不是通過組選擇的書籍 – user3124172

+0

確定嗎? 'update_all' [聲稱尊重條件](http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all)。你能粘貼生成的SQL嗎? – Ben

+0

所以經過一番研究,不能在更新語句中使用group。 這是我得到: UPDATE'books' JOIN ON chapters.book_id = books.id設置章節'long_book' =真 ......注意,它被遺漏了的基和具有 – user3124172

1

下面是使用Rails 4查詢,ActiveRecord的

Book.includes(:chapters).references(:chapters).group('books.id').having('count(chapters.id) > 10')