【问题标题】:SQL Server 2008 R2: Multiple UNION on different databases table'sSQL Server 2008 R2:不同数据库表上的多个 UNION
【发布时间】:2016-03-30 12:50:45
【问题描述】:

我有两个数据库,即db1db2

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

下表是一些演示记录。

数据库db1 表格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 表格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 表格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 所有三个表的以下查询,但出现性能问题。 db1中也有test2,test3

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;

请告诉我是否需要修改?

【问题讨论】:

  • 能否附上execution plan的截图?
  • @vkp,对不起!我的错。
  • union 中的查询 1 和 2 是否不同?
  • @vkp,除数据库名称外相同。
  • union 是必要的,它需要额外检查重复项,还是 union all 足够?

标签: sql sql-server sql-server-2008 sql-server-2008-r2 union


【解决方案1】:

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

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

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

3) 将查询更改为仅从镜像表中选择

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

【讨论】:

    【解决方案2】:

    当您不担心消除重复记录时,UNION ALL 将比 UNION 执行得更好,因为您避免了昂贵的不同排序操作。

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多