MySQL子查询/加入

时间:2012-01-30 13:25:04

标签: mysql join subquery

好的我有一个90%的查询,它只是在“where子句”中出现“未知列a.UserID”的错误我已经阅读过试图对问题进行排序并发现内部的SQL进程它不会知道我将表A设置为什么因此是问题但是我的知识和专业知识使我的工作变得不可行。我已经尝试了另一种使用JOIN的路线,但总是回到同样的问题。

查询是:

SELECT 
  a.*, 
  (SELECT AVG(c.PlayerTime)
   FROM (
     SELECT PlayerTime 
     FROM elite_highscores b 
     WHERE a.UserID = b.UserID
     ORDER BY PlayerTime ASC LIMIT 10
   ) c
  ) AS avgtime, 
  MIN(PlayerTime) as besttime, 
  MAX(TimeAdded) as time, 
  COUNT(UserID) 
FROM elite_highscores a
WHERE Publish = 'Yes' 
GROUP BY UserID HAVING COUNT(UserID) >= 10 
ORDER BY avgtime ASC

所以基本上我要做的是从高分榜中选择一些数字(对于记录超过10个高分的用户)并计算平均时间(平均时间),但仅基于该球员的最后10分这就是导致我这个问题的原因,其他一切似乎都运转正常。

表格结构:

ScoreID int(16) 
UserID int(10) 
PlayerScore int(16) 
Publish enum('No', 'Hidden', 'Expired', 'Yes')
TimeAdded int(16) 
PlayerIP varchar(18) 
Country varchar(2) 
PlayerTime int(10) 
code varchar(50)

1 个答案:

答案 0 :(得分:1)

SELECT 
  a.UserID, 
  last10.avgtime, 
  MIN(a.PlayerTime) AS besttime, 
  MAX(a.TimeAdded)  AS time, 
  COUNT(*) 
FROM 
      elite_highscores a 
  JOIN
      ( SELECT b.UserID,
               AVG(b.PlayerTime) AS avgtime 
        FROM
              ( SELECT DISTINCT UserID
                FROM elite_highscores 
              ) da
          JOIN
              elite_highscores b 
            ON  b.UserID = da.UserID
            AND b.PlayerTime <=
                ( SELECT c.PlayerTime
                  FROM elite_highscores c
                  WHERE c.UserID = da.UserID
                  ORDER BY c.PlayerTime ASC 
                  LIMIT 1 OFFSET 9
                ) 
        GROUP BY b.UserID 
      ) last10
    ON last10.UserID = a.UserID 
WHERE a.Publish = 'Yes' 
GROUP BY a.UserID 
ORDER BY avgtime ASC