2014-10-20 46 views
0

是否有一种更简单的方法来计算满足相同条件的不同表中的行数?对多个表进行条件计数

例如,我要单独计算行的下面两个表中分别对应特定的ID的数量的:

Select 
'table1' as tablename, count(*) as rownr from table1 
where SOMEID in ('1815972751','1815751159','1815752967','1815756079') 

union all 

Select 
'table2' as tablename, count(*) as rownr from table2 
where SOMEID in ('1815972751','1815751159','1815752967','1815756079') ; 

结果会是这样的

table1 | 21 
table2 | 54 

然而,我只想定义条件(在这种情况下,ID)一次,例如在一个变量或列表中,因此它们的区域易于管理。

回答

2

这里有一种方法:

select tablename, count(*) 
from (select 'table1' as tablename, someid 
     from table1 
     union all 
     select 'table2' as tablename, someid 
     from table2 
    ) t 
where someid in ('1815972751', '1815751159', '1815752967', '1815756079') 
group by tablename; 

请注意,性能可能不如在你原来的版本一样好。

+0

谢谢,作品像魅力! – Cos 2014-10-20 15:45:37

相关问题