3

考虑这样的 SQL 查询

SELECT Temp.rating, Temp.avgage
FROM (SELECT S.rating, AVG (S.age) AS avgage
FROM Sailors S 
GROUP BY S.rating) AS Temp
WHERE Temp.avgage = (SELECT MIN (Temp.avgage)
FROM Temp)

MySQL 监视器给出了这个错误:

错误 1146 (42S02): 表 'testDB.Temp' 不存在

我应该怎么做才能避免这个错误?

4

1 回答 1

1
SELECT Temp.rating, Temp.avgage 
FROM 
  ( SELECT S.rating, AVG(S.age) AS avgage
    FROM Sailors S 
    GROUP BY S.rating
  ) AS Temp
WHERE Temp.avgage = 
      ( SELECT MIN (Temp.avgage)
        FROM Temp                --- the error is here
      )

根据您想要处理关系的方式,您可以使用:

SELECT Temp.rating, Temp.avgage 
FROM 
  ( SELECT S.rating, AVG(S.age) AS avgage
    FROM Sailors S 
    GROUP BY S.rating
  ) AS Temp
ORDER BY Temp.avgage 
LIMIT 1

或更简单的等价物:

SELECT S.rating, AVG(S.age) AS avgage
FROM Sailors S 
GROUP BY S.rating
ORDER BY avgage 
LIMIT 1

或者这个(显示所有并列结果):

SELECT Temp.rating, Temp.avgage 
FROM 
  ( SELECT S.rating, AVG(S.age) AS avgage
    FROM Sailors S 
    GROUP BY S.rating
  ) AS Temp
WHERE Temp.avgage = 
      ( SELECT AVG(S.age) AS avgage
        FROM Sailors S 
        GROUP BY S.rating
        ORDER BY avgage 
        LIMIT 1              
      )
于 2012-01-18T23:33:09.040 回答