Mysql与计数和数学有很多对很多

时间:2010-06-29 20:26:21

标签: sql mysql

我的mysql数据库中有很多表设置。团队可以在许多游戏中,每个游戏有2个团队。他们之间有一个名为teams_games的表。

我要做的是为每个团队创建统计数据。理想的打印输出是:

team_id,team_name,胜利,失败,平局,错误

我的问题是将哪支球队的主场或客场的数学与他们的胜利联系起来,然后计算出来。然后,我必须总结那些与每支球队离开并获胜的次数。然后最后将所有东西加在一我当前的查询结构(无法正常工作)与创建表信息一起在下面。有什么想法吗?

SELECT t.*, COUNT(g_wins.home_score > g_wins.away_score) AS wins, COUNT(g_wins.home_score < g_wins.away_score) AS losses FROM teams as t JOIN teams_games AS t_g_wins ON t_g_wins.tid = t.tid JOIN games AS g_wins on t_g_wins.gid = g_wins.gid"

Table Create Table

 teams  CREATE TABLE `teams` (
 `tid` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(60) NOT NULL,
`league` varchar(2) NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`tid`)

teams CREATE TABLE `teams` ( `tid` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(60) NOT NULL, `league` varchar(2) NOT NULL, `active` tinyint(1) NOT NULL, PRIMARY KEY (`tid`)

)

CREATE TABLE teams_games (

teams_games

`tid` int(10) unsigned NOT NULL,
`gid` int(10) unsigned NOT NULL,
`homeoraway` tinyint(1) NOT NULL,
PRIMARY KEY (`tid`,`gid`),
KEY `gid` (`gid`),
CONSTRAINT `teams_games_ibfk_1` FOREIGN KEY (`tid`) REFERENCES `teams` (`tid`),
CONSTRAINT `teams_games_ibfk_2` FOREIGN KEY (`gid`) REFERENCES `games` (`gid`)

`tid` int(10) unsigned NOT NULL, `gid` int(10) unsigned NOT NULL, `homeoraway` tinyint(1) NOT NULL, PRIMARY KEY (`tid`,`gid`), KEY `gid` (`gid`), CONSTRAINT `teams_games_ibfk_1` FOREIGN KEY (`tid`) REFERENCES `teams` (`tid`), CONSTRAINT `teams_games_ibfk_2` FOREIGN KEY (`gid`) REFERENCES `games` (`gid`)

)

1 个答案:

答案 0 :(得分:2)

你使事情变得复杂:这应该是一个2-n而不是n-m的关系。 摆脱teams_games表并将2个字段添加到游戏桌,例如:home_tidaway_tid

编辑:然后查询类似:

select t.tid, t.name, 
       sum(g.home_score < g.away_score xor t.tid = g.home_tid) wins, 
       sum(g.home_score > g.away_score xor t.tid = g.home_tid) losses, 
       sum(g.home_score = g.away_score) draws
  from games g
       join teams t on t.tid = g.home_tid or t.tid = g.away_tid
 group by t.tid

所以答案是使用sum,否则它会计算输出中的true和false值,即连接产生的总行数。

EDIT2

select t.tid, t.name, 
       sum(g.home_score < g.away_score xor tg.homeoraway) wins, 
       sum(g.home_score > g.away_score xor tg.homeoraway) losses, 
       sum(g.home_score = g.away_score) draws
  from games g
  join team_games tg on tg.gid = g.gid
  join teams t on t.tid = tg.tid
 group by t.tid