Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference to temporary relation from qualification list

Consider an SQL query like this

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 monitor gives this error:

ERROR 1146 (42S02): Table 'testDB.Temp' doesn't exist

What should I do to avoid this error?

like image 580
bfaskiplar Avatar asked Aug 04 '26 16:08

bfaskiplar


1 Answers

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
      )

Depending on how you want to handle ties, you could just use:

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

or the simpler equivalent:

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

or this one (that shows all tied results):

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              
      )
like image 114
ypercubeᵀᴹ Avatar answered Aug 08 '26 03:08

ypercubeᵀᴹ