对多个表中的多个值求和

时间:2011-07-12 00:32:44

标签: sql postgresql

我想做一个SQL查询来获取一个和号,但我不知道如何构造这个查询。

select count(*) from table1 where commom_fk in (1234);
select count(*) from table2 where commom_fk in (1234);
select count(*) from table3 where commom_fk in (1234);
select count(*) from table4 where commom_fk in (1234);
select count(*) from table5 where commom_fk in (1234);

我想在一个查询中总结这些结果,这是一种方法吗?

谢谢大家。 ----- *

回答了这个问题。 但是,如果我想用多个common_fk来做这个?

1 个答案:

答案 0 :(得分:5)

SELECT     
      ( SELECT ...)
    + ( SELECT ...)
    + ( SELECT ...)
    + ( SELECT ...)
    + ( SELECT ...)    
  AS sumAll

或拥有全部5个结果:

SELECT     
      ( SELECT ...) AS sum1
    , ( SELECT ...) AS sum2
    , ( SELECT ...) AS sum3
    , ( SELECT ...) AS sum4
    , ( SELECT ...) AS sum5