数据库查询以从单个查询中的不同表中获取计数总和

时间:2010-12-16 06:26:19

标签: java mysql database database-design

我在Mysql数据库中编写一个查询,其中 查询1返回计数(),表示结果为10 和 查询2返回Count(),表示结果为30

但是我希望得到40的结果,这是两者的总和

我有什么选择让单个查询给我结果。

2 个答案:

答案 0 :(得分:4)

你应该使用UNION ALL来结合相同的数值,例如30 + 30。

select SUM(n) as total
from (
  (select count(*) as n from table1)
  UNION ALL
  (select count(*) as n from table2)
) t;

答案 1 :(得分:1)

select sum(num) as total
from (
  (select count(*) as num from table1)
  UNION ALL
  (select count(*) as num from table2)
) a;
相关问题