[英]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.