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

MySQL查询-where子句中的未知列-执行where子句时可能尚未确定列值,mysql,Mysql,我试图从Another表中获取字段和相关计数,但上面的查询不起作用。该查询涉及两个不同的表和应用程序。上面的查询有错误,我正在寻找实现这一点的替代方法 WHERE子句中没有列cont的别名。您将希望使用类似于以下内容的内容: SELECT area_id, area_name, (select count(*) from applications where claims_status=1 and

我试图从Another表中获取字段和相关计数,但上面的查询不起作用。该查询涉及两个不同的表和应用程序。上面的查询有错误,我正在寻找实现这一点的替代方法

WHERE子句中没有列cont的别名。您将希望使用类似于以下内容的内容:

 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
请尝试此查询

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
获取每个中心名称的计数,然后联接表以获取每个区域的计数

使用have而不是where

因为这是别名的问题


From:

where子句中的未知列“cont”。错误代码:1054。“字段列表”中的未知列“c.cnt”……我已将c.cont0更改为c.cnt0……其工作原理……我今天学到的另一种方法……谢谢……但这是最佳优化的吗?只是问..@user1854007问题是,当您在SELECT中为某些内容提供别名时,它在WHERE中不可用,因此您必须解决它。如果您确定应用程序表中始终有匹配的行,则具有左联接的第二个版本也可以更改为内部联接。编写查询的方法有很多,您只需找出最适合您的情况的方法即可:
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
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;
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”.