【问题标题】:Index for SQL joinSQL 连接的索引
【发布时间】:2017-01-08 17:09:20
【问题描述】:

我正在对 3 个表进行联接,但由于某种原因,我无法在其中一个表上使用索引。

这里是查询:

SELECT * FROM nfl_schedules ns
join nfl_daily_fantasy_players dfs
    on dfs.date = ns.date and dfs.team = ns.home_team
left join fantasy_salaries sal
    on sal.platform_id = (SELECT id FROM platforms p WHERE p.platform = 'draft_kings') and sal.game_key = ns.game_key and  sal.player_id = dfs.player_id
left join nfl_players np
    on np.player_id = dfs.player_id
where ns.timeframe = @frame;

我在 dfs 上为 (date, team) 和 (date, team, player_id) 字段创建了索引,但两者都没有被应用。它是唯一没有应用索引的表。在额外的它说它正在使用哪里。

有什么想法吗?

id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,PRIMARY,dfs,ALL,"date_team,date_team_player_id",NULL,NULL,NULL,4920,"Using where"
1,PRIMARY,ns,ref,"date_team_timeframe,date_team",date_team_timeframe,264,"draftcrunch_new.dfs.date,draftcrunch_new.dfs.team",1,"Using index condition"
1,PRIMARY,sal,ref,"unique,index3,index4,index5",index4,262,"draftcrunch_new.dfs.player_id,draftcrunch_new.ns.game_key",1,"Using where"
1,PRIMARY,np,ref,"unique_players,index3",unique_players,4,draftcrunch_new.dfs.player_id,1,NULL
2,SUBQUERY,p,const,platform,platform,257,const,1,"Using index"

【问题讨论】:

  • 发布解释计划
  • 不确定格式化它的最佳方式。但它就在那里。在第一行,它没有使用 dfs 的索引。
  • 你能在dfs上展示你的create index语句吗?
  • 我使用了 mysqlworkbench GUI,但索引如下:(date, team, player_id), (player_id), (date, team)
  • 我建议尝试进一步隔离这一点。将您的查询缩小到 2 个表连接。如果症状仍然存在,请发布两个表的show create table 输出和相应的解释计划。另一方面,如果症状仅在您加入所有这些表时显示,那么这也是一个很好的信息。

标签: mysql indexing


【解决方案1】:
where  ns.timeframe = @frame        --> INDEX(timeframe)
ON dfs.date = ns.date and  dfs.team = ns.home_team
                                    --> INDEX(team, date)
WHERE  p.platform = 'draft_kings'   --> INDEX(platform)
sal.platform_id = ( SELECT...)      --> Use JOIN, not IN
sal.platform_id = ...
      and  sal.game_key = ns.game_key
      and  sal.player_id = dfs.player_id
                 --> INDEX(game_key, player_id, platform_id) (in any order)
ON np.player_id = dfs.player_id     --> INDEX(player_id)

记住:

  • PRIMARY KEY 是 UNIQUE 键是 INDEX;
  • 当您有INDEX(a), INDEX(a,b) 时,第一个是多余的。

Index cookbook.

如果您需要更多帮助,请为每个表提供SHOW CREATE TABLE。

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 2013-12-01
    • 2012-06-03
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2017-05-02
    • 2014-09-11
    相关资源
    最近更新 更多