如果我有查询,例如:
select column1, (
select count(*) from table2
) as some_count
from table1
where column1 = 'foo'
我可以在where子句中使用column1
,但是如果我尝试添加
and some_count > 0
然后我收到some_count
不存在的错误。我怎样才能在where子句中使用它?
答案 0 :(得分:12)
使用HAVING
select column1, (
select count(*) from table2
) as some_count
from table1
HAVING some_count > 0
答案 1 :(得分:3)
原样,唯一的方法是使用派生表:
SELECT x.*
FROM (select column1,
(select count(*) from table2) as some_count
from table1
where column1 = 'foo') x
WHERE x.some_count > 0
你是否意识到没有相关性,some_count
将为返回的每一行返回相同的值?