我在较大的查询中有一个子选择,我正尝试使用CASE语句将计算字段添加到子选择中。
我的子选择如下:
LEFT JOIN
(
SELECT Course_ID, Question_ID, Answer, (HIP =
CASE
WHEN Question_ID = 77 THEN "1"
WHEN Question_ID = 78 THEN "2"
WHEN Question_ID = 79 THEN "3"
WHEN Question_ID = 80 THEN "4"
WHEN Question_ID = 81 THEN "5"
WHEN Question_ID = 82 THEN "6"
ELSE "Undefined HIP"
END)
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
) ercehip
ON course.Course_ID = ercehip.Course_ID
当我尝试在父选择语句中访问ercehip.HIP时,它说它是未定义的。关于如何解决这个问题的任何想法?谢谢
答案 0 :(得分:1)
HIP = (..)
。CASE .. WHEN()
仅在检查Question_ID
,因此您可以将其移到Case
子句之外,从而使查询变得不太冗长。请尝试以下操作:
(
SELECT Course_ID, Question_ID, Answer,
(CASE Question_ID
WHEN 77 THEN "1"
WHEN 78 THEN "2"
WHEN 79 THEN "3"
WHEN 80 THEN "4"
WHEN 81 THEN "5"
WHEN 82 THEN "6"
ELSE "Undefined HIP"
END) AS HIP
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
) AS ercehip
答案 1 :(得分:1)
您必须根据MySQL语法的要求确定计算字段的别名
SELECT Course_ID, Question_ID, Answer, (
CASE
WHEN Question_ID = 77 THEN "1"
WHEN Question_ID = 78 THEN "2"
WHEN Question_ID = 79 THEN "3"
WHEN Question_ID = 80 THEN "4"
WHEN Question_ID = 81 THEN "5"
WHEN Question_ID = 82 THEN "6"
ELSE "Undefined HIP"
END) as HIP
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
OR
SELECT Course_ID, Question_ID, Answer, (
CASE
WHEN Question_ID = 77 THEN "1"
WHEN Question_ID = 78 THEN "2"
WHEN Question_ID = 79 THEN "3"
WHEN Question_ID = 80 THEN "4"
WHEN Question_ID = 81 THEN "5"
WHEN Question_ID = 82 THEN "6"
ELSE "Undefined HIP"
END) HIP
FROM proposals.new_gen_ed_answers
WHERE Answer = 1