纠正这个问题

时间:2012-01-25 09:30:51

标签: mysql sql

为什么查询不起作用

SELECT (sum(`result` = 1)/count(id) * 100) as `abc`,  
case 
  when `abc` > 80 then 'pass'
  when `abc` < 80 then 'fail'
end as `abcd` 
FROM `user_quiz_answers` WHERE `user_quiz_id` = 39

表格

id          int(11)         AUTO_INCREMENT                                  
question_id     int(11)                                             
result      tinyint(1)

错误:

#1054 - Unknown column 'abc' in 'field list'

我管理了这个但不是上面的

SELECT 
case 
  when (sum(`result` = 1)/count(id) * 100) > 80 then 'pass' 
  when (sum(`result` = 1)/count(id) * 100) < 80 then 'fail' 
end as `abcd` 
FROM `user_quiz_answers` WHERE `user_quiz_id` = 39

1 个答案:

答案 0 :(得分:3)

因为您不能在同一查询中使用列别名作为列名。 像这样的东西会起作用

SELECT
  `abc`,
  case 
    when `abc` > 80 then 'pass'
    when `abc` < 80 then 'fail'
  end as `abcd` 
FROM (
  SELECT (sum(`result` = 1)/count(id) * 100) as `abc`
  FROM `user_quiz_answers` WHERE `user_quiz_id` = 39
) AS sq

其他更简单的方法来做你似乎想做的事情:

SELECT 
  IF((sum(`result` = 1)/count(id) * 100) > 80, 'pass','fail') as `abcd`
FROM `user_quiz_answers` WHERE `user_quiz_id` = 39