我有这样的表建立一个数据库的游戏结果:SQL查询性能
Table Players
id ... name
1 .... Alice
2 .... Bob
3 .... Charlie
... etc
Table Games
Player1 Player2 myscore oppscore result
1 ... 3 .... 25 ... 18 .... W
3 ... 2 .... 15 ... 20 .... L
2 ... 1 .... 17 ... 17 .... T
myScore的指PLAYER1,oppscore指Player2
我想返回一个玩家的最频繁的查询对手,以及他们之间的输赢记录。 (我与每个对手第二个查询的输赢记录。)
所以我用这个:
SELECT count(*) p2.name "Opponent",
FROM games, players p1, players p2
WHERE p1.name = ?
AND games.gametype = ?
AND games.player1 = p1.id
AND games.player2 = p2.id
GROUP BY player2, gametype
ORDER BY count(*) DESC
为了拿起所有游戏(不管是谁PLAYER1 和谁是player2)我店每场比赛两次: 即我真有:
Player1 Player2 myscore oppscore result
1 ... 3 .... 25 ... 18 .... W
3 ... 1 .... 18 ... 25 .... L
3 ... 2 .... 15 ... 20 .... L
2 ... 3 .... 20 ... 15 .... W
2 ... 1 .... 17 ... 17 .... T
1 ... 2 .... 17 ... 17 .... T
我想消除数据的冗余,从而 减少一半的数据库大小。
我试过了(其中g1是类似游戏的表格,但是删除了冗余行的 )。
create view gv as
select * from g1
union
select
player2 player1,
player1 player2,
(case when result = 'T' then 'T'
when result = 'W' then 'L'
when result = 'L' then 'W'
end) result,
oppscore myscore,
myscore oppscore
from g1
然后做我的查询反对gv而不是反对游戏。
其中的工作...除了它需要(基于一个例子), 超过10倍(游戏0.10秒,vs 1.4秒 为gv)。
有没有更好的方法来做到这一点?
您可以发布您针对该视图运行的查询吗? –
这是相同的查询 - 只是使用视图名称(gv)而不是表名(游戏)。 –