MySQL以不同的方式使用Count

标签 mysql sql database

我研究过这段代码:

select *,
  year(curdate())-year(dbirth) - (right(curdate(),5) < right(dbirth,5)) as age 
from       resident_info 
having age = 18;

但我想要的是在获得所有已经 18 的信息后我想数一下它们。有什么方法可以同时输入两个查询或解决我的问题吗?非常感谢

最佳答案

除非我遗漏了一些东西,如果您需要这些的计数,那么您可以使用:

select count(*)
from
(
  select *,
   year(curdate())-year(dbirth) - (right(curdate(),5) < right(dbirth,5)) as age 
  from       resident_info 
 having age = 18
) src

如果您想返回 resident_infocount 中的所有数据,则可以使用 CROSS JOIN:

select *, 
   year(curdate())-year(dbirth) - (right(curdate(),5) < right(dbirth,5)) as age,
   src.Total
from resident_info 
cross join
(
    select count(*) Total
    from
    (
        select year(curdate())-year(dbirth) - (right(curdate(),5) < right(dbirth,5)) as age 
        from  resident_info 
        having age = 18
    ) x
) src
having age = 18

关于MySQL以不同的方式使用Count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15071726/

相关文章:

mysql - 违反完整性约束 (LEETO14.SYS_C00414504)

sql - 如何返回 SQL Server 存储过程的计算(聚合)结果

asp.net - 错误 : the details of the application error from being viewed remotely

sql - 如何以某种方式对这些 SQL 结果进行排序?

mysql - 从子查询中获取 2 个结果

java - 实体映射中的重复列,oneToMany 关系

php - 使用 PHP 在 MySQL 数据库中存储多个复选框数据

php - 将新行追加到 MySQL 查询调用的 HTML 表,并更新 MySQL 中的当前列

mysql - 如何在 sequelize 上使用 mysql REPLACE 执行搜索?

mysql - SQL - EXISTS 和 NOT EXISTS 不等式