Rails SQL查询计数

时间:2014-03-06 00:09:54

标签: sql ruby-on-rails ruby

我有一个名为“书籍”的表格,其中有很多“章节”,我希望得到所有超过10章的书籍。如何在单个查询中执行此操作?

到目前为止,我有这个......

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

3 个答案:

答案 0 :(得分:1)

以下是使用Rails 4,ActiveRecord

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

答案 1 :(得分:0)

我不太了解rails,但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')

更新:我明白了。这里我在rails中做了什么,如果它可以帮助任何人

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)

答案 2 :(得分: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)