为什么我会得到笛卡尔积而不是加入?

时间:2011-06-11 11:53:59

标签: php mysql

以下代码应该返回前五名玩家在游戏中所做的平均数。

SELECT "Starting 5" as Flag, 
       count(gs.ID) as Games, 
       avg(s.min) as Min, 
       avg(s.P2M) as P2M, 
       avg(s.P2A) as P2A, 
       100*avg(s.P2M/s.P2A) as P2P,  
       avg(s.P3M) as P3M,  
       avg(s.P3A) as P3A,  
       100*avg(s.P3M/s.P3A) as P3P,  
       avg(s.FTM) as FTM,  
       avg(s.FTA) as FTA,  
       100*avg(s.FTM/s.FTA) as FTP,  
       avg(s.OFFENSE) as OFFENSE,  
       avg(s.DEF) as DEF,  
       avg(s.TOT) as TOT,  
       avg(s.AST) as AST,  
       avg(s.TO) as 'TO',  
       avg(s.ST) as ST,  
       avg(s.FV) as FV,  
       avg(s.CM) as CM,  
       avg(s.PTS) as PTS,  
       avg(s.P2M - s.P2A + s.P3M - s.P3A + s.FTM - s.FTA + s.TOT + s.AST + s.ST + s.FV + s.PTS - s.TO - s.CM) as EFF  
FROM gamesstats AS gs 
    INNER JOIN gamesstatsplayers as gp ON gs.id=gp.GameStatID 
    INNER JOIN players as p ON gp.PlayerID = p.ID 
    INNER JOIN stats as s ON gp.stat=s.id 
                         WHERE gs.HomeTeamID ='664' 
                         and gs.HomeScore > gs.VisitorScore 
                         and gp.IsHomePlayer = 1 
                         AND gp.IsFirst5 = 1 
                         AND gs.SeasonStart = '2010' 
                         AND gs.LeagueID = '145' 

我应该得到4场比赛和平均每场比赛。我得到的是游戏中每个玩家的平均值。这意味着我得到了20场比赛,并且每场比赛我想要的平均值的1/5。问题是由于某种原因它使得笛卡尔产品而不是加入。尝试找几个小时的虫子,但似乎无法找到它。

表格说明:

gamestats用于举办每场比赛。

gamesstatsplayers通过GameStatID连接到游戏,并负责每个游戏中的每个玩家统计数据。

球员是所有球员的桌子。

stats是一张只包含统计数据的表格,gamesstats有一个指向统计数据的链接,可以为您提供游戏中整个团队的统计数据(2个链接,一个用于家庭,一个用于访问者),gamesstatsplayers有一个指向统计数据的链接给你1场比赛中1名球员的统计数据。 (这意味着统计数据是两件事)。

2 个答案:

答案 0 :(得分:1)

在不知道架构的情况下,这是一个猜测,但你可能需要对GameStatID进行分组,如果这是游戏的主键。

答案 1 :(得分:0)

首先,您应该使用WHERE子句:

SELECT "Starting 5" as Flag, 
       count(gs.ID) as Games, 
       avg(s.min) as Min, 
       avg(s.P2M) as P2M, 
       avg(s.P2A) as P2A, 
       100*avg(s.P2M/s.P2A) as P2P,  
       avg(s.P3M) as P3M,  
       avg(s.P3A) as P3A,  
       100*avg(s.P3M/s.P3A) as P3P,  
       avg(s.FTM) as FTM,  
       avg(s.FTA) as FTA,  
       100*avg(s.FTM/s.FTA) as FTP,  
       avg(s.OFFENSE) as OFFENSE,  
       avg(s.DEF) as DEF,  
       avg(s.TOT) as TOT,  
       avg(s.AST) as AST,  
       avg(s.TO) as 'TO',  
       avg(s.ST) as ST,  
       avg(s.FV) as FV,  
       avg(s.CM) as CM,  
       avg(s.PTS) as PTS,  
       avg(s.P2M - s.P2A + s.P3M - s.P3A + s.FTM - s.FTA + s.TOT + s.AST + s.ST + s.FV + s.PTS - s.TO - s.CM) as EFF  
FROM gamesstats AS gs 
    INNER JOIN gamesstatsplayers as gp ON gs.id=gp.GameStatID 
    INNER JOIN players as p ON gp.PlayerID = p.ID 
    INNER JOIN stats as s ON gp.stat=s.id 
    WHERE
     gs.HomeTeamID ='664' 
     and gs.HomeScore > gs.VisitorScore 
     and gp.IsHomePlayer = 1 
     AND gp.IsFirst5 = 1 
     AND gs.SeasonStart = '2010' 
     AND gs.LeagueID = '145'