[英]How to take sum of two different query result counts in mysql?
我需要从类别+子类别+子子类别中获取文件总数
为此,我使用自己的视图编写了这种查询。
select ((select count(*) from view_category where 1=1)+ (select count(*) from view sub category where 1=1) + (select count(*) from view subsub category where 1=1)) as cnt
它的返回计数值。 但我想知道还有其他更好的方法可用来获得相同的结果。
我尝试过这种方式,但是不起作用( 如何在MySQL中对多个子查询行进行SUM()?
select sum(int_val) from((select count(*) from view_category where 1=1) as int_val union (select count(*) from view sub category where 1=1) as int_val union (select count(*) from view subsub category where 1=1) as int_val )
。
您不需要进行联合,并且可以将每个别名作为自己的别名...只要每个查询仅返回一行,您就可以做各种疯狂的事情。 通过忽略任何“ join”条件,您将获得笛卡尔结果,但是笛卡尔结果为1:1:1:1的结果只有1条记录
select
ByCat.CatCount
+ BySubCat.SubCatCount
+ BySubSubCat.SubSubCatCount as Cnt
from
( select count(*) CatCount
from view_category ) ByCat,
( select count(*) SubCatCount
from view_sub_category) BySubCat,
(select count(*) SubSubCatCount
from view_subsub_category ) BySubSubCat
还要想象一下,如果您还需要其他元素的sum()或AVG()计数...您可以将它们放入一行,并根据需要使用。
如果表具有相似的结构,则可以使用UNION
合并结果,然后执行一个COUNT(*)
。
这对我有用
select count(*) from(
(select count(*) from view_category where 1=1) union (select count(*) from view sub category where 1=1) union (select count(*) from view subsub category where 1=1) ) AS int_val;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.