0
 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

我正在尝试从另一个表中获取字段和相关计数,但上述查询不起作用。查询涉及两个不同的表(apparea,applications)。上面的查询有错误,我正在寻找实现此目的的替代方法。

4

3 回答 3

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

这也可以使用 a 来编写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
于 2013-03-06T10:39:20.627 回答
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 的计数,然后加入表以获取每个区域的计数

于 2013-03-06T10:40:12.030 回答
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

于 2013-03-06T10:53:27.793 回答