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

标签 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

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

最佳答案

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

关于MySQL 查询 - where 子句中的未知列 - 执行 WHERE 子句时可能尚未确定列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15244943/

相关文章:

mysql - Spring Boot MySQL Docker Caused by : java.net.ConnectException: Connection refused(连接被拒绝)

php - PHP-MySQL 中处理的日期时间/时间戳

MySQL查看 "flattens"数据

php - 使用 if 条件更新表 - PHP - MySQL

mysql - 如何编写查询以在我的 sql 中获取如下所示的输出

php - 带有 JSON、PHP 的 iOS

php - 我只能下载表头,不能下载FPDF中MYSQL数据库的数据

php - MySQL-将日期插入varchar,然后在查询时转换回日期

mysql - 在一行中加入列

MySQL设计一对多?