2010-04-15 37 views

回答

2

你試過類似的東西嗎?

select sum(val) from (
    select sum(col1) as val from table1 where criteria1 = 'x' 
    union all 
    select sum(col2) from table2 where criteria2 = 'y' 
    union all 
    select sum(col3) from table3 where criteria3 = 'z' 
    union all 
    select sum(col4) from table4 where criteria4 = 'w' 
) newTbl 
+0

在一些數據庫中的結合命令自動刪除重複的行。如果你從兩個表中得到相同的總和,這將是一個問題。使用'union all'來保留重複項。 – BenV 2010-04-15 13:47:38

+0

好點。編輯我的答案。 – MJB 2010-04-15 13:49:22

+0

我用這種方式,我得到了這種類型的錯誤。 #1248 - 每個派生表必須有自己的別名 是的,它是這樣嗎?還有一件事'union all'在mysql中工作? – Karthik 2010-04-15 13:52:12

0

使用派生表 - 你可能想做這樣的事情,所以你得到所有結果在一行!

select 
    u.user_count, 
    c.country_count 
from 
(
    select count(*) as user_count from users where username like 'f%' 
) u 
join 
(
    select count(*) as country_count from country 
) c; 

更comlpex例如:http://pastie.org/921407

相關問題