首页 > 解决方案 > 索引了 1500 万客户,但查询仍然需要将近 5 分钟才能返回结果

问题描述

我在 3 列中有 1500 万个客户数据,每列都有索引:

  1. 顾客
    • Index ix_disabled_customer_id on zen_customers(customers_id, disabled);
  2. 客户属性
    • Index ix_attribute_id_and_name onzen_customers(attribute_id, attribute_name);
  3. 客户属性值。
    • Index ix_attribute_id_and_customer_id on `zen_customers`(customers_id, attribute_id);

我正在尝试使用 Gender 过滤客户,并且返回结果需要很长时间。

以下是查询

SELECT tcav.customers_id AS customers_id 
FROM customer_attribute_value tcav
JOIN customer_attribute tca
JOIN customers zc
WHERE tcav.attribute_id = tca.attribute_id
    AND tca.attribute_name = "Gender"
    AND tcav.attribute_value = "M"
    AND zc.customers_id = tcav.customers_id
    AND  zc.disabled = 0;

为解释扩展计划添加了图像

如果我能得到优化此过滤的想法,我将不胜感激。谢谢

标签: mysqlquery-optimizationentity-attribute-value

解决方案


首先,建议使用 ON 子句而不是 WHERE 子句来连接表。它不太可能对性能产生任何影响,但它确实有助于提高查看哪些列与哪些表相关联的能力。

SELECT tcav.customers_id AS customers_id 
FROM tulip_customer_attribute_value tcav
JOIN tulip_customer_attribute tca
ON tcav.attribute_id = tca.attribute_id
JOIN zen_customers zc
ON zc.customers_id = tcav.customers_id
WHERE tca.attribute_name = "Gender"
AND tcav.attribute_value = "M"
AND zc.disabled = 0

添加以下索引:

tulip_customer_attribute (attribute_name,attribute_id)

tulip_customer_attribute_value (attribute_id,attribute_value,customers_id)

索引中列的顺序很重要。


推荐阅读