MySQL查询 - 执行WHERE子句时可能尚未确定where子句列值的未知列

时间:2013-03-06 10:36:10

标签: mysql

 SELECT area_id, 
           area_name,
           (select count(*) from applications
                  where claims_status=1 and 
                    center_name=c.area_id) as cont
    FROM apparea c where cont<>0

我正在尝试从其他表中获取字段和相关计数,但上述查询无法正常工作。该查询涉及两个不同的表(服装,应用程序)。上面的查询有错误,我正在寻找实现这一目标的替代方法。

3 个答案:

答案 0 :(得分:1)

cont子句中没有列WHERE的别名。你会想要使用类似的东西:

SELECT area_id, 
  area_name,
  cont
FROM
(
  SELECT area_id, 
    area_name,
    (select count(*) 
     from applications
     where claims_status=1 
     and center_name=c.area_id) as cont
  FROM apparea c
) c 
where cont<>0

这也可以使用LEFT JOIN

编写
select c.area_id,
  c.area_name,
  a.cont
from apparea c
left join
(
  select count(*) cont,
    center_name
  from applications
  where claims_status=1 
  group by center_name
) a
  on c.area_id = a.center_name

答案 1 :(得分:0)

尝试此查询

SELECT 
     c.area_id,
     c.area_name,
     cnt 
FROM 
     apparea c, 
     (select 
            center_name, 
            count(*) AS cnt 
     from 
            applications
     where 
            claims_status=1 
     GROUP BY 
            center_name
     HAVING 
            count(*) > 0)  cont
where 
     c.area_id = cont.center_name;

获得每个center_name的计数,然后连接表以获取每个区域的计数

答案 2 :(得分:0)

使用HAVING而不是where

因为aliases存在问题。

It is not permissible to refer to a column alias in a WHERE clause, because the column
value might not yet be determined when the WHERE clause is executed. 
See Section C.5.5.4, “Problems with Column Aliases”. 

http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

来自: http://dev.mysql.com/doc/refman/5.0/en/select.html

相关问题