Mysql 性能不佳的查询需要帮助
我有下面的查询,它工作正常,但速度非常慢,返回结果的速度不够快,无法满足我的需要 它显示了11个位置中最常挑选的9名球员 有人认为有更好的写作方法吗Mysql 性能不佳的查询需要帮助,mysql,Mysql,我有下面的查询,它工作正常,但速度非常慢,返回结果的速度不够快,无法满足我的需要 它显示了11个位置中最常挑选的9名球员 有人认为有更好的写作方法吗 select PlayerName, RankName, Position from ( select Opener1 as Player from Team where CompetitionIDAuto = 1 union all select Opener2 as Player from Team where CompetitionIDAut
select PlayerName, RankName, Position
from
(
select Opener1 as Player from Team
where CompetitionIDAuto = 1
union all
select Opener2 as Player from Team
where CompetitionIDAuto = 1
union all
select Bat1 as Player from Team
where CompetitionIDAuto = 1
union all
select Bat2 as Player from Team
where CompetitionIDAuto = 1
union all
select Bat3 as Player from Team
where CompetitionIDAuto = 1
union all
select WK as Player from Team
where CompetitionIDAuto = 1
union all
select AR1 as Player from Team
where CompetitionIDAuto = 1
union all
select Bowl1 as Player from Team
where CompetitionIDAuto = 1
union all
select Bowl2 as Player from Team
where CompetitionIDAuto = 1
union all
select Bowl3 as Player from Team
where CompetitionIDAuto = 1
union all
select Bowl4 as Player from Team
where CompetitionIDAuto = 1
) a
Inner Join Player on a.Player = Player.PlayerIDAuto
Inner Join RankValue on Player.ODIRank = RankValue.RankIDAuto
Inner Join PlayerPosition on Player.ODIPosition = PlayerPosition.PlayerPositionIDAuto
group by PlayerName
order by count(*) desc
Limit 0,9
请尝试一下:
select PlayerName, RankName, Position
from
(
select CONCAT('|', Opener1, '|', Opener2, '|', Bat1, '|', Bat2, '|', Bat3, '|', WK, '|', AR1, '|', Bowl1, '|', Bowl2, '|', Bowl3, '|', Bowl4, '|') as Player from Team
where CompetitionIDAuto = 1
) a
Inner Join Player on LOCATE(CONCAT('|', Player.PlayerIDAuto, '|'), a.Player) <> 0
Inner Join RankValue on Player.ODIRank = RankValue.RankIDAuto
Inner Join PlayerPosition on Player.ODIPosition = PlayerPosition.PlayerPositionIDAuto
group by PlayerName
order by count(*) desc
Limit 0,9
至于表的标准化,如果可能的话,我认为@Tom是正确的。如果我正确理解了您的问题,最好的策略是将主源表一分为二,而不是:
PlayerID_role1 PlayerID_role2 PlayerID_role3 ... CompetitionIDAuto
一个桌面团队看起来像:
PlayerID RoleID CompetitionID
再加上一个单独的表格,例如从竞赛到自动记数竞赛,其中包括所有其他竞赛信息,例如
CompetitionIDAuto CompetitionName CompetitionDate...
然后您可以执行如下查询:
select PlayerName, RankName, Position from Team where CompetitionIdAuto = 1
Inner Join Player on Team.PlayerID = Player.PlayerIDAuto
Inner Join RankValue on Player.ODIRank = RankValue.RankIDAuto
Inner Join PlayerPosition on Player.ODIPosition = PlayerPosition.PlayerPositionIDAuto
group by Player.PlayerIDAuto
order by count(*) desc
Limit 0,9
注意:不要按PlayerName分组,因为我想PlayerDauto是一个自动递增的主索引字段,而PlayerName很可能根本不是索引。根据定义,按非索引字段分组的速度很慢。您也可以对当前表上的查询进行此改进。我建议对数据进行规范化。不是每个位置都有一个表,每个表都有一个字段,而是要有一个表,其中包含字段的团队、位置和球员。这对于查询来说会更有效率。谢谢,与我的查询结果完全相同。没有问题——我没有想到其他任何东西。谢谢,似乎是最明智的选择。很高兴听到我的原始查询没有遗漏任何明显的内容。