带有两个INNER JOIN的MariaDB SQL COUNT执行时间太长

时间:2018-01-29 13:18:26

标签: mysql count inner-join

编辑:我已经了解了EXPLAIN。我还想确定players_teams在查询中没有索引项。我已经在我的查询中添加了一个,现在它的执行时间不到一秒。

评论仍然会受到赞赏。

我对我正在尝试编写的数据库进行查询,它应该返回玩家在一个赛季中玩过的游戏数量。

我一直遇到查询问题,这些问题会返回多个不同games_id或不同team_id的条目。

我终于得到了我想要的结果,但查询现在需要3分钟来执行。

以下是目前为止(编辑过)的查询:

SELECT COUNT(DISTINCT schedule_player_status.id) AS ps_id
FROM schedule_player_status
INNER JOIN schedule ON schedule.id = schedule_player_status.ps_game_id
    AND schedule.s_season_id = ".$seasonID."
    AND schedule.s_datetime < NOW()
    AND schedule.s_type='GAME'
INNER JOIN players_teams ON players_teams.t_team_id = schedule_player_status.ps_team_id
    AND players_teams.t_season_id = ".$seasonID."
    AND players_teams.t_player_id = schedule_player_status.ps_player_id
    AND (players_teams.t_player_class = 'ROSTER' OR players_teams.t_player_class = 'SPARE')
WHERE schedule_player_status.ps_season_id=" . $seasonID . "
    AND schedule_player_status.ps_status = 'IN'
GROUP BY schedule_player_status.ps_player_id

它是更大查询(已编辑)的一部分:

SELECT players.p_name, players.p_email, players.p_phone, players.p_dob, players.p_status, players_teams.t_player_position,
players.id AS playerID, teams.id AS teamID, teams.t_name, teams.t_div,

/*Count games played*/
(SELECT COUNT(DISTINCT schedule_player_status.id) AS gamesPlayed
FROM schedule_player_status
players_teams.t_player_class = 'SPARE')
INNER JOIN schedule ON schedule.id = schedule_player_status.ps_game_id
    AND schedule.s_season_id = ".$seasonID."
    AND schedule.s_datetime < NOW()
    AND schedule.s_type='GAME'
INNER JOIN players_teams ON players_teams.t_team_id = schedule_player_status.ps_team_id
    AND players_teams.t_season_id = ".$seasonID."
    AND players_teams.t_player_id = schedule_player_status.ps_player_id
    AND (players_teams.t_player_class = 'ROSTER' OR 
WHERE schedule_player_status.ps_season_id=".$seasonID."
    AND schedule_player_status.ps_status = 'IN'
    AND schedule_player_status.ps_player_id = playerID
) AS gamesPlayed,

/*Count goals by playerID*/
SUM(players_stats.s_goals) AS s_goals,

/*Count assists by playerID*/
SUM(players_stats.s_assists) AS s_assists,

/*Count PIMs by playerID*/
SUM(players_stats.s_pims) AS s_pims

FROM `players_teams`

LEFT JOIN `players` ON players.id = players_teams.t_player_id
LEFT JOIN `players_stats` ON players_stats.s_player_id = players.id 
    AND players_stats.s_season_id = ".$seasonID." 
    AND players_stats.s_team_id = players_teams.t_team_id
LEFT JOIN `teams` ON teams.id = players_teams.t_team_id AND teams.t_season_id = " . $seasonID . "

WHERE players_teams.t_season_id = ". $seasonID ." AND (players_teams.t_player_class = 'ROSTER' OR players_teams.t_player_class = 'SPARE')

GROUP BY playerID

当我执行较大的查询时,它会在5分钟时超时。

我确定查询结构很糟糕,这是我写过的第一个查询之一。

感谢您提供的任何帮助。

马特

0 个答案:

没有答案