mssql 涉及多张表名不同其余一样的表条件查询,如何快速获取过滤后的总数?

2019-09-05 08:22发布

问题:

例子如下:A B 表结构一样 ,实际不止两张表,也许5张10张这样的。

1. 

select (

(select count(1) from A as a where  a.xxx=xxx left join C as c on  a.xxx=c.xxx)+(select count(1) from A as b where  b.xxx=aa left join C as c on  b.xxx=c.xxx)

)as total

发现这样表多了,很耗时。

 

2.

select count(1)

from

select xxx from A as a where a.xxx=xxxx

union all 

select xxx from B as b where b.xxx=xxxx

)as t

left join C as c on  t.xxx=c.xxx

where 

c.id=xxx

求高手,求dba.

回答1:

select sum(qty) from (select count(1) as qty from a union all select count(1) as qty from b)