1
在每个表中都有许多具有数量的行。像这样,我在每张表中都有不同数量的金额。每个表字段名称是不同的。我怎样才能得到一个查询中的四个表中的所有值的总和?有什么方法吗?如何从单个查询中的四个不同表中获得总数
在每个表中都有许多具有数量的行。像这样,我在每张表中都有不同数量的金额。每个表字段名称是不同的。我怎样才能得到一个查询中的四个表中的所有值的总和?有什么方法吗?如何从单个查询中的四个不同表中获得总数
你试过类似的东西吗?
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
使用派生表 - 你可能想做这样的事情,所以你得到所有结果在一行!
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
在一些数据库中的结合命令自动删除重复的行。如果你从两个表中得到相同的总和,这将是一个问题。使用'union all'来保留重复项。 – BenV 2010-04-15 13:47:38
好点。编辑我的答案。 – MJB 2010-04-15 13:49:22
我用这种方式,我得到了这种类型的错误。 #1248 - 每个派生表必须有自己的别名 是的,它是这样吗?还有一件事'union all'在mysql中工作? – Karthik 2010-04-15 13:52:12