sql计数总和

问题描述

| 我有两个表,并希望每个表中的总行数。实际查询更为复杂,因为每个计数都会有where ...子句 如何在t-sql中执行以下操作(两者均无效)?
select count(*) from table1 + count(*) from table2
要么
select sum(count(*) from table1,count(*) from table2)
    

解决方法

select  (select count(PrimaryKeyID) from  FirstTable) 
      + (select COUNT(PrimaryKeyID) from TableSecond)
所以我认为我们应该避免在下面的查询中使用星号。因为这可能会导致查询性能下降
select  (select count(*) from  FirstTable) 
      + (select COUNT(*) from TableSecond)
    ,
select SUM(cnt) from
(
    select COUNT(*) as cnt from table1 where /* where conditions */
    union all
    select COUNT(*) from table2 where /* where conditions */
) t
看起来可以解决问题,将不同表的查询分开,并轻松扩展到更多表。