探索者的博客
2022-12-18 11:35:02 1614

mysql count 统计多表数据

作者头像 探索者
mysql 统计多表
-------------------------------------------------------------------------------------------

select * from ((select count(*) as countnum from a_admin_code where classid=6) a,(select count(*) as countnum from a_admin_code_class where fid=1) b,(select count(*) as countnum from a_admin_company)c )


countnum   countnum   countnum
3		5		1


select a.countnum+b.countnum+c.countnum as allnum from ((select count(*) as countnum from a_admin_code where classid=6) a,(select count(*) as countnum from a_admin_code_class where fid=1) b,(select count(*) as countnum from a_admin_company)c )

allnum
9

统计一张表-------------------------------------------------------------------------------------------

SELECT a.classid,count(*) as tjnum,b.classname,b.id FROM `a_admin_code` as a left join a_admin_code_class as b on a.classid=b.id group by classid
-------------------------------------------------------------------------------------------

union all统计多表
现在需要把它们汇总加起来,可以使用如下方法实现
SELECT COUNT(cnt) FROM (
SELECT COUNT(id) AS cnt FROM test_0 WHERE field1 = 1
UNION ALL
SELECT COUNT(id) AS cnt FROM test_1 WHERE field1 = 1
.
.
.
UNION ALL
SELECT COUNT(id) AS cnt FROM test9 WHERE field1 = 1
) AS countdata

注:为UNION ALL的所有表做一个别名是必须的,虽然这个别名并没有什么意义
但如果没有的话mysql会报出错误:Every derived table must have its own alias
-------------------------------------------------------------------------------------------
mysql count多表数据总和
SELECT a.countNum + b.countNum + c.countNum
FROM (
(SELECT COUNT(*) AS countNum FROM table_a) a,
(SELECT COUNT(*) AS countNum FROM table_b) b,
(SELECT COUNT(*) AS countNum FROM table_c) c
)

mysql count 统计多表数据

评论区

评论者头像

张三

2025-06-16

非常实用的文章,我学到了很多关于前端性能优化的知识。特别是缓存策略部分,对我帮助很大。

评论者头像

李四

2025-06-15

代码分割确实是提高前端性能的重要手段,请问作者有没有实际项目中遇到的代码分割最佳实践可以分享?

作者头像
探索者 作者
2025-06-16

感谢提问!在实际项目中,我通常会根据路由、组件和第三方库进行代码分割。对于大型组件库,可以考虑使用动态导入来实现按需加载。