SQL连接索引

时间:2016-09-01 00:25:56

标签: mysql indexing

我在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;

我有字段(date, team)(date, team, player_id)的dfs索引,但都没有应用。它是唯一没有应用索引的表。在额外它说它正在使用的地方。

有什么想法吗?

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"

1 个答案:

答案 0 :(得分:0)

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 KEYUNIQUE密钥,是INDEX;
  • 当你有INDEX(a), INDEX(a,b)时,第一个是多余的。

Index cookbook

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