1

我有这个小的 SQL 查询。

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 子句'中的未知列'grade'

但是,如果我删除最后第二行,它工作正常。我已经尝试过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
4

2 回答 2

4

Sql 语句在某种程度上按以下顺序进行评估:

  • 在哪里
  • 选择
  • 团体
  • 拥有
  • 命令

因此,您在 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
于 2009-04-28T10:09:12.483 回答
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
于 2009-04-28T10:08:04.670 回答