SQL Server 2008 R2:不同数据库上的多个 UNION table

SQL Server 2008 R2: Multiple UNION on different databases table's

我有两个数据库,即 db1db2

数据库db1包含1个table,即test1,数据库db2包含两个table,即test2test3.

下面是table的一些演示记录。

数据库db1 Table: test1

Create table test1
(
    ID int,
    hrs int,
    dates date,
    st_date date,
    ed_date date
);

insert into test1 values(1,10,'2000-01-01','1900-01-01','2016-01-01');
insert into test1 values(2,20,'2000-02-01','1900-01-01','2016-01-01');
insert into test1 values(3,30,'2000-03-01','1900-01-01','2016-01-01');
insert into test1 values(4,40,'2000-04-01','1900-01-01','2016-01-01');

数据库: db2 Table: test2

create table test2
(
    ID int,
    ID2 int
);

insert into test2 values(1,11);
insert into test2 values(2,22);
insert into test2 values(3,33);
insert into test2 values(4,44);

数据库: db2 Table: test3

create table test3
(
    ID int,
    date date
);

insert into test3 values(1,'2000-01-01');
insert into test3 values(2,'2000-02-02');
insert into test3 values(3,'2000-03-03');
insert into test3 values(4,'2000-04-04');

注意:现在我正在通过 union 所有三个 table 执行以下查询,但出现性能问题。还有 test2test3 table 出现在 db1

select nm,sum(x.avghrs)
from
(
select t1.nm, sum(hrs) as avghrs
from db2.test3 t3,
     db2.test2 t2,
     db1.test1 t1
where t1.id = t2.id
    t3.id = t2.id
group by t1.nm

union

select t1.nm, sum(hrs) as avghrs
from db1.test3 t3,
     db1.test2 t2,
     db1.test1 t1
where t1.id = t2.id
    t3.id = t2.id
group by t1.nm

union

select nm, 0 as avghrs
from test1
where dates between st_date and ed_date
) x

group by nm;

请告诉我是否需要修改?

我认为问题与驻留在不同数据库中的表的列之间的 JOIN 有关。您可以尝试以下方法:

1) 镜像单个数据库中的表(复制模式和数据)

2) 应用适当的索引(至少包含 JOIN 中使用的 ID)

3) 将您的查询更改为 SELECT 仅来自镜像表

此外,您需要对联合结果执行不同的操作吗?如果不是,应将 UNION 替换为 UNION ALL 以避免隐式 DISTINCT。

当您不担心消除重复记录时,UNION ALL 的性能优于 UNION,因为您避免了昂贵的不同排序操作。