MySQL 索引不工作(用例特定场景)

标签 mysql indexing explain

到目前为止,以下是我的场景:

参数 由用户控制:(这些参数由仪表板控制,但出于测试目的,我创建了 sql 参数以更改它们的值)

    SET @device_param := "all devices";
    SET @date_param_start_bar_chart := '2016-09-01';
    SET @date_param_end_bar_chart := '2016-09-19';
    SET @country_param := "US";
    SET @channel_param := "all channels";
在后端运行的

查询

SELECT 
  country_code,
  channel_report_tag,
  SUM(count_more_then_30_min_play) AS '>30 minutes',
  SUM(count_15_30_min_play) AS '15-30 Minutes',
  SUM(count_0_15_min_play) AS '0-15 Minutes' 
FROM
  channel_play_times_cleaned 
WHERE IFNULL(country_code, '') = 
  CASE
    WHEN @country_param = "all countries" 
    THEN IFNULL(country_code, '') 
    ELSE @country_param 
  END 
  AND IFNULL(channel_report_tag, '') = 
  CASE
    WHEN @channel_param = "all channels" 
    THEN IFNULL(channel_report_tag, '') 
    ELSE @channel_param 
  END 
  AND iFnull(device_report_tag, '') = 
  CASE
    WHEN @device_param = "all devices" 
    THEN iFnull(device_report_tag, '') 
    ELSE @device_param 
  END 
  AND playing_date BETWEEN @date_param_start_bar_chart 
  AND @date_param_end_bar_chart 
GROUP BY channel_report_tag 
ORDER BY SUM(count_more_then_30_min_play) DESC 
limit 10 ;

我应用的索引

CREATE INDEX my_index 
ON channel_play_times_cleaned (
  country_code,
  channel_report_tag,
  device_report_tag,
  playing_date,
  channel_report_tag
)

我点击了这个链接:My SQL Index Cook-Book Guide创建我的索引。

但是执行上述查询时的 EXPLAIN 关键字告诉我没有使用索引。

enter image description here

我想知道我在这里做错了什么?

最佳答案

  1. 您在前 3 个 where 条件中使用函数和 case 表达式。不能使用简单的字段索引来加速此类查找。

  2. MySQL 可能会为 playing_date 条件使用索引,但该字段不是引用索引中的最左边,因此引用索引也不适合它。

如果我是你,我会从 where 条件中删除逻辑,并通过构建这样一个 sql 语句将其移动到应用程序层,该语句已解决 case 条件并仅发出必要的 sql。

关于MySQL 索引不工作(用例特定场景),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573499/

相关文章:

java - 通过java函数向MySQL插入数据

performance - SQLite索引导致查询性能下降

mysql - 使得主键+常量可以使用索引

MySQL 删除外键索引时抛出错误。

.net - 无符号与带符号的数字作为索引

mysql - 无法理解如何在基本 MYSQL 解释示例中摆脱表扫描

未使用 mysql 5.1.37 查询索引

sql - 什么会导致合法的 MySql INSERT INTO 命令失败?

MySQL错误1045, "Access denied for user '用户'@'localhost'(使用密码: YES)"

mysql - 意外的类型,期望的名称