我认为我已将我的数据库规范化,超出了我的SQL知识。 :) 这是我在斯诺克联盟网络应用程序中遇到的一个问题。它计算了来自所有赛季的球队高中断的总体统计数据。在示例团队ID 3中。
select max(break_score) maxBreak,avg(break_score) avgBreak, count(break_score) breaks from breaks join matches on match_id=break_match where break_player in ( select distinct player_id from players join team_members on player=player_id and team=3) and (match_hometeam=3 or match_awayteam=3)
表:
match_id int(11) auto_increment match_hometeam int(11) match_awayteam int(11) match_date date match_void tinyint(4) match_status tinyint(4) match_homescore tinyint(4) match_awayscore tinyint(4) match_league int(11)
break_id int(11) auto_increment break_match int(11) foreign key to match_id break_player int(11) break_score tinyint(4) break_clearance tinyint(4) break_year int(11)
team int(11) foreign key to teams table player int(11) foreign key to players table year int(11) the year that the player played for the team
除了一个问题之外,上面的查询几乎按预期工作。如果一名球员已经为一支以上的球队效力,那么他对所有球队的分数将被纳入这些统计数据中。
如果Breaks表有一个额外的字段'break_team',那么查询将是微不足道的。所以我的问题是双重问题,任何人都可以协助正确的查询,还是应该减少规范化以帮助这些统计数据?什么时候去标准化?
答案 0 :(得分:2)
我没有随时可用的MySQL安装,但您所追求的可能是EXISTS条款,试试这个并回复它是否需要处理您需要的内容:
select max(break_score) maxBreak, avg(break_score) avgBreak, count(break_score) breaks
from breaks
join matches on match_id=break_match
where exists(select 1
from players
join team_members on player=player_id and team=3
where break_year = year
and break_player = player_id
and (match_hometeam=3 or match_awayteam=3))