mysql - 如何使用外表编写子查询

标签 mysql subquery

我需要编写一个 MySQL 查询来获取每个月的帐户数量、新帐户数量和旧帐户数量。 旧帐户的条件描述为 cond1。

我已经尝试过:

select month(a.ct) as month,
count(select id from a where cond1) as oldAccount,
count(select id from a where !cond1) as newAccount
from accounts a
where ~conditions~
group by month(a.ct)

它并不完全有效。

一般来说,我需要知道如何在子查询中使用外表。 谁能帮助我吗?

最佳答案

通常,count() 会进入子查询内部:

select month(a.ct) as month,
      (select count(id) from a where cond1) as oldAccount,
      (select count(id) from a where !cond1) as newAccount
from accounts a
where ~conditions~
group by month(a.ct);

但是,外部查询中有一个聚合,因此这有点复杂。您的关联条件大概是在 ID 上而不是在月份上。这种不一致会影响上面的查询。

最好的方法可能是将其表达为join,但这可能取决于条件。否则,您可以使用子查询:

select month(a.ct) as month,
       sum(oldAccount), sum(newAccount)
from (select a.*,
             (select count(id) from a where cond1) as oldAccount,
             (select count(id) from a where !cond1) as newAccount
      from accounts a
      where ~conditions~
     ) t
group by month(a.ct);

编辑:

如果通过 a,您想要外部 accounts 表,则只需使用条件聚合:

select month(a.ct) as month,
      sum(cond1) as oldAccount,
      sum(!cond1) as newAccount
from accounts a
where ~conditions~
group by month(a.ct);

关于mysql - 如何使用外表编写子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33650863/

相关文章:

php - 从包含表的多个值的字段中排除一个值

PHP问卷计算设计

mysql - sql查询根据排序顺序重新排序数据

c# - 在 System.Data.SqlCommand (C#) 中使用子查询 - 语法错误,在 SQL Server Mgmt Studio 中工作

java - HQL Select 可以在另一个查询的结果集上吗?

mysql - 将sql查询转换为mySql,需要每个类别的前5条记录

MySQL (PHPMyAdmin) REGEXP , PHP 之间的区别

mysql - MySQL 和 Sphinx 混合查询

MySQL 子查询真的很慢......解决方法?

mysql - 如何为子查询添加值?