是否有更简单的方法来计算满足相同条件的不同表中的行数?
例如,我想分别计算以下两个表中与某些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),例如在变量或列表中,因此它们的区域易于管理。
答案 0 :(得分: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;
请注意,性能可能不如原始版本那么好。