首页 > 这两条sql语句能不能组合成一条

这两条sql语句能不能组合成一条

select count(1) from student where age>20;
select count(1) from student where age<=20;
类似这两个查询,能不能合成一条查询?
我感觉这两个查询需求遍历一次student表就足够了,用union all应该也要遍历两次吧。
请问那个sql大神说下,能不能查一次就能取出两个数据。


select sum(case when age>20 then 1 else 0 end) as h_age,sum(case when age<=20 then 1 else 0 end) as l_age from student;

由于我这边没有mysql,所以还没有经过测试,只是提供个思路


或者用个判断也行


select sum(age>20) age1, sum(age<=20) age2 from student;
【热门文章】
【热门文章】