简体   繁体   中英

SQL 'Invalid column name ' error, with inner select

i have the following 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' 

and i get the error Invalid column name 'ethnicity' referring to the last reference to that column.

Question: How come this column is not available to the WHERE clause?

I know that if i do the following, it works:

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'  

You cannot use "Computed" columns in your where clause without specifically referencing the entire computation (query, case, etc).

You should join the Query table instead of subquerying it:

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'

You can't use a column name you've just assigned in the SELECT clause in the following WHERE clause. As a general case you can put it in a subquery and then use the column name:

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' 

This query might be better suited to a JOIN though:

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' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM