在MySQL where子句中使用生成的列

时间:2010-08-11 22:44:56

标签: mysql where-clause

如果我有查询,例如:

select column1, (
    select count(*) from table2
) as some_count
from table1
where column1 = 'foo'

我可以在where子句中使用column1,但是如果我尝试添加

and some_count > 0

然后我收到some_count不存在的错误。我怎样才能在where子句中使用它?

2 个答案:

答案 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将为返回的每一行返回相同的值?