SQL'无效列名'错误,内部选择

时间:2013-11-19 10:43:29

标签: sql sql-server

我有以下SQL:

SELECT A.*, 
(SELECT answer FROM [tblAnswers] B 
WHERE  B.memberID = A.memberID AND QuestionID = 3) AS ethnicity
FROM [tblMembers] A  
WHERE 
LOWER(gender) = 'm' 
AND ethnicity = 'Sephardi' 

我收到错误Invalid column name 'ethnicity',指的是该列的最后一个引用。

问题:WHERE条款无法使用此列?

我知道,如果我执行以下操作,它就会起作用:

SELECT A.*, 
(SELECT answer FROM [tblAnswers] B WHERE  B.memberID = A.memberID AND QuestionID = 3) AS ethnicity
FROM [tblMembers] A  
WHERE
LOWER(gender) = 'm' 
AND convert(nvarchar, (SELECT answer FROM [tblAnswers] B WHERE  B.memberID = A.memberID AND QuestionID = 3)) = 'Sephardi'  

2 个答案:

答案 0 :(得分:3)

您不能在where子句中使用“Computed”列,而不能专门引用整个计算(查询,大小写等)。

您应该加入Query表而不是子查询它:

Select A.*, B.answer
From tblMembers A
    Inner Join tblAnswers B on A.memberID = B.membeID and A.QuestionID = 3
Where Lower(gender) = 'm'
    and B.answer = 'Sephardi'

答案 1 :(得分:2)

您不能使用您刚刚在以下SELECT子句中的WHERE子句中指定的列名。作为一般情况,您可以将其放在子查询中,然后使用列名:

SELECT * FROM
(
    SELECT A.*, 
    (SELECT answer FROM [tblAnswers] B 
    WHERE  B.memberID = A.memberID AND QuestionID = 3) AS ethnicity
    FROM [tblMembers] A  
    WHERE LOWER(gender) = 'm' 
) s
WHERE ethnicity = 'Sephardi' 

此查询可能更适合JOIN

SELECT A.*, t.answer AS ethnicity
FROM [tblMembers] A  
LEFT JOIN tblAnswers t ON b.memberID = A.memberID AND QuestionID = 3
WHERE LOWER(gender) = 'm' AND t.answer = 'Sephardi'