【发布时间】:2015-11-04 07:49:34
【问题描述】:
我有一个看起来像这样的桌子“游戏”:
桌面游戏:
id (int)
home_team (varchar)
away_team (varchar)
home_goals (int)
away_goals (int)
对于特定匹配,我需要获取以下内容:
主队:
home wins
home tie
home loss
home scored
home conceded
因为我还需要知道上述所有实体的总数(胜利、失败、得分等),所以我基本上需要与上述相同,但是当球队在客场比赛时,所以:
away wins
away tie
away loss
away scored
away conceded
客队:
away wins
away tie
away loss
away scored
away conceded
因为我还需要知道以上所有实体的总数(赢、输、得分等),所以我基本上需要和上面一样,但是当球队在主场比赛时,所以:
home wins
home tie
home loss
home scored
home conceded
最好的办法是在一个查询中获得所有这些信息。恐怕这会很困难。所以我可以想象我需要进行多重查询。 目前我有 2 个查询只是为了获取主场球队的数据:
select
count(case when home_goals > away_goals then 1 else null end) as state_win
,count(case when home_goals < away_goals then 1 else null end) as state_loss
,count(case when home_goals = away_goals then 1 else null end) as state_tie
,sum(home_goals) as state_scored
,sum(away_goals) as state_conceded
from
game
where
home_team = 'chelsea'
select
count(case when home_goals < away_goals then 1 else null end) as other_win
,count(case when home_goals > away_goals then 1 else null end) as other_loss
,count(case when home_goals = away_goals then 1 else null end) as other_tie
,sum(away_goals) as other_scored
,sum(home_goals) as other_conceded
from
game
where
away_team = 'chelsea'
我的计划是将查询 1 中的统计信息与查询 2 相加,以获得总数。 有没有办法只做一次这个查询?我尝试了 union,但我不确定它是正确的方法。
【问题讨论】:
-
这个问题之前肯定有人问过和回答过。
-
是否可以在数据库中存储额外的信息?因为似乎最简单的解决方案就是为每场比赛存储主队积分(3、1 或 0),从而实现更快、更简单的 SELECT。
标签: mysql