我研究过这段代码:
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_info
和 count
中的所有数据,则可以使用 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/