我怎样才能加快这个查询?

时间:2016-02-10 14:32:00

标签: sql ruby-on-rails activerecord

我有一个有效的记录查询

Catalog::Product.joins(:product_properties).where("catalog_product_properties.name != ''").uniq.count

他生成了这个sql

SELECT DISTINCT COUNT(DISTINCT "catalog_products"."id") FROM "catalog_products" INNER JOIN "catalog_product_properties" ON "catalog_product_properties"."catalog_product_id" = "catalog_products"."id" WHERE (catalog_product_properties.name != '')

谁执行~1.8秒

我尝试重写这个,我有这个

Catalog::Product.connection.select_all("SELECT COUNT(*) FROM (SELECT DISTINCT catalog_products.id FROM catalog_products INNER JOIN catalog_product_properties ON catalog_product_properties.catalog_product_id = catalog_products.id WHERE (catalog_product_properties.name != '')) AS temp")

谁执行约1秒,但它仍然太长。两个表有大约200k记录,我怎么能加快?

抱歉我的英文不好

2 个答案:

答案 0 :(得分:0)

此查询:

SELECT DISTINCT COUNT(DISTINCT "catalog_products"."id")
FROM "catalog_products" INNER JOIN
     "catalog_product_properties"
      ON "catalog_product_properties"."catalog_product_id" = "catalog_products"."id"
WHERE (catalog_product_properties.name != '')

不需要join(假设适当的外键关系)。它可以写成:

SELECT COUNT(DISTINCT "catalog_products_properties"."catalog_product_id")
FROM "catalog_product_properties"
WHERE (catalog_product_properties.name <> '')

反过来,此查询可以从catalog_product_properties(name, catalog_product_id)上的索引中受益。

唉,我不熟悉Ruby,但这不应该很难表达。

答案 1 :(得分:0)

你应该把它写成:

Catalog::ProductProperty.where("catalog_product_properties.name != ''").count(:catalog_product_id, distinct: true)