2010-04-15 39 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

相关问题