Mysql Many to Many with Count and math
I have a many to many table setup in my mysql database. Teams can be in many games and each game has 2 teams. There is a table in between them called teams_games.
What I am looking to do is create stats for each team. An ideal printout would be:
team_id, team_name, wins, losses, draws, error
My problem is linking the math of which team is the home or away and if they won, then counting those up. I would then have to sum those with the count of times each team was away and won. Then finally join everything together. My current query structure(which doeasn't work correctly) is below along with the Create Table information. Any thoughts?
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
J开发者_JAVA百科OIN 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`)
)
CREATE TABLE
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`)
)
CREATE TABLE
games
(
`gid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`location` varchar(60) NOT NULL,
`time` datetime NOT NULL,
`description` varchar(400) NOT NULL,
`error` smallint(2) NOT NULL,
`home_score` smallint(2) DEFAULT NULL,
`away_score` smallint(2) DEFAULT NULL,
PRIMARY KEY (`gid`)
)
You are complicating things: this should be a 2-n not n-m relationship.
Get rid of teams_games
table and make 2 fields to games table, ex: home_tid
and away_tid
EDIT: and the query would be then something similar:
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
so the answer is to use sum, otherwise it counts both true and false values in output which is total rows resulting from joins.
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
精彩评论