My question is related to Rails, but even a generic SQL answer would be helpful.
I deal with four tables: categories, books, categories and books. The category has and belongs to many books. Books have many recipes.
In translating Rails code, I:
class Category < ActiveRecord::Base has_and_belongs_to_many :books end class Book < ActiveRecord::Base has_and_belongs_to_many :categories has_many :recipes end class Recipe < ActiveRecord::Base belongs_to :book end
I am trying to get all the recipes contained in books in this category.
I know how to do this with many queries, but not with one query. With many requests, I would do:
recipes = [] books = @category.books books.each do |book| recipes << book.recipes.flatten end
I do not like this because it requires N + 1 queries. I probably need to join in to do everything at once, but I'm not sure of the syntax in ActiveRecord or SQL. I am using MySQL.
source share