2009-04-28 55 views
1

我有這個小的SQL查詢。爲什麼我可以對內聯SELECT值進行排序,但不能在WHERE子句中使用它?

SELECT a.`id` , a.`title` , a.`date` , 
(
    SELECT MAX(grade) 
    FROM tests 
    WHERE userid = 41 
    AND presid = a.`id` 
) AS grade 
FROM `presentations` a 
WHERE a.`visible` = 1 
AND `grade` >= 5 
ORDER BY `grade` DESC 

這給我的錯誤

1054 - 未知列 '品位' 在 'where子句'

但如果我刪除第二個最後一行,它工作正常。我試圖做AND a.grade,甚至給測試表一個名字,並追加這個名字來評分,但仍然沒有運氣。

如何在WHERE子句中使用此內嵌查詢?

我發現這是有效的,但它是唯一的方法嗎?

SELECT a.`id` , a.`title` , a.`date` , 
(
    SELECT MAX(grade) 
    FROM tests 
    WHERE userid = 41 
    AND presid = a.`id` 
) AS grade 
FROM `presentations` a 
WHERE a.`visible` = 1 
AND (
    SELECT MAX(grade) 
    FROM tests 
    WHERE userid = 41 
    AND presid = a.`id` 
) >= 5 
ORDER BY `grade` DESC 

回答

5

SQL語句是按照下面的順序評價稍微:

  • FROM
  • WHERE
  • SELECT
  • GROUP
  • HAVING
  • ö RDER

因此,您在SELECT子句中定義的內容在WHERE子句中不可用。您需要將該約束放入HAVING子句中:

SELECT a.`id` , a.`title` , a.`date` , 
(
    SELECT MAX(grade) 
    FROM tests 
    WHERE userid = 41 
    AND presid = a.`id` 
) AS grade 
FROM `presentations` a 
WHERE a.`visible` = 1 
HAVING `grade` >= 5 
ORDER BY `grade` DESC 
+0

There we we :)謝謝 – 2009-04-28 10:12:24

0
SELECT a.`id` , a.`title` , a.`date` , 
     (
     SELECT MAX(grade) 
     FROM tests 
     WHERE userid = 41 
       AND presid = a.`id` 
     ) AS grade 
FROM `presentations` a 
WHERE a.`visible` = 1 
HAVING `grade` >= 5 
ORDER BY 
     `grade` DESC 
相關問題