[英]SQL 'Invalid column name ' error, with inner select
i have the following SQL: 我有以下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. 我得到错误
Invalid column name 'ethnicity'
指的是对该列的最后引用。
Question: How come this column is not available to the WHERE
clause? 问题:为什么此列不可用于
WHERE
子句?
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). 如果不专门引用整个计算(查询,大小写等),则不能在where子句中使用“计算”列。
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. 您不能使用在以下
WHERE
子句中的SELECT
子句中刚分配的列名。 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: 但是,此查询可能更适合于
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.