我有一个模型产品,它属于一个类别(产品表中的 category_id)。我想编写一个查询,它采用前 20 个产品及其类别名称。我有两种获取方式:
使用
includes
,像这样:Product.includes(:category). order(:updated_at). limit(20)
并在 View 中获取类别名称,如下所示:
<%= product.category.name if product.category %>
这将创建这样的查询:
SELECT `products`.* from `products` ORDER BY `products`.updated_at LIMIT 20 SELECT `categories`.* from `categories` WHERE `categories`.id IN (1,2,3,4,5..,25)
像这样使用
连接
:Product.joins("LEFT JOIN categories ON categories.id = products.category_id"). select("products.*, categories.name as category_name"). order(:updated_at). limit(20)
并在这样的 View 中使用它:
<%= product.category_name %>
这将生成如下查询:
SELECT products.*, categories.name as category_name from `products` LEFT JOIN categories ON categories.id = products.category_id ORDER BY `products`.updated_at LIMIT 20
方法 1 的优点是我们可以使用在类别模型上编写的模型级方法,并且代码更易于维护。但它的缺点是它使用单独的查询来查找使用 IN 子句的类别。
哪个是首选方式?
最佳答案
这不仅仅是偏好,而是性能与可维护性的问题。我会首先为您的查询选择更易于维护的路线。如果您的性能开始因某些查询而受到影响,请使用连接语法或从头开始编写普通的旧 sql 进行优化。不要过早优化。优化您发现实际需求的地方。
关于mysql - 哪个是首选,:includes or :joins?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057490/