[英]How to take sum of two different query result counts in mysql?
I need to take total count of files from category + sub category + subsub category 我需要从类别+子类别+子子类别中获取文件总数
For that I write this kind of a query using my views. 为此,我使用自己的视图编写了这种查询。
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
Its returning count value. 它的返回计数值。 But I want to know any other better method is available to get the same result.
但我想知道还有其他更好的方法可用来获得相同的结果。
I tried this way but its not working ( How to SUM() multiple subquery rows in MySQL? ) 我尝试过这种方式,但是不起作用( 如何在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 )
. 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 )
。
you don't need to do a union, and can just have each as its own from alias... As long as each query is returning only one row, you can do all sorts of crazy things. 您不需要进行联合,并且可以将每个别名作为自己的别名...只要每个查询仅返回一行,您就可以做各种疯狂的事情。 By ignoring any "join" condition, you get a Cartesian result, but a Cartesian of 1:1:1 will result with only 1 record
通过忽略任何“ 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
Also imagine if you needed sum() or AVG() counts too from other elements... You could get those into a single row and use however you needed. 还要想象一下,如果您还需要其他元素的sum()或AVG()计数...您可以将它们放入一行,并根据需要使用。
如果表具有相似的结构,则可以使用UNION
合并结果,然后执行一个COUNT(*)
。
This is working for me 这对我有用
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.