具有相同列和相同where子句的两个表的联合

时间:2013-05-09 23:12:40

标签: sql sql-server-2008

我在两个不同的位置有两个SQL表,它们包含完全相同的字段,只有不同的数据(所有唯一的SKU)。我想加入表并在结果上运行一个复杂的WHERE子句以进行日志记录。

我有什么工作,但看起来很多余(我来自C#背景)。

select sku, catalogname, getDate()
from uswebdb.commerce.catalogproducts
where sku is not null
and (CategoryName is not null or ParentOID = 113)
and (sku not like '%[a-z]%')
union all
select sku, catalogname, getDate()
from ukwebdb.commerce.catalogproducts
where sku is not null
and (CategoryName is not null or ParentOID = 113)
and (sku not like '%[a-z]%')

是否有更简洁的方法来加入这两个表并产生类似的结果,或者这是最好的方法?所选字段将始终相同,但所涉及的表的数量和where子句的复杂性可能会在不久的将来增加。

我想理想情况下我想看到这样的事情:

select sku, catalogname, getDate() from
uswebdb.commerce.catalogproducts
--magic join/union--
ukwebdb.commerce.catalogproducts
-- more joins...--
where sku is not null
and (CategoryName is not null or ParentOID = 113)
and (sku not like '%[a-z]%')

在SQL2008中甚至可以吗?我真的过分思考这个吗?

2 个答案:

答案 0 :(得分:2)

这些是在不同的服务器上还是在不同的数据库中,因为它会产生很大的不同。您的语法意味着它们位于同一服务器上,不同的数据库中,这意味着您可以将WHERE移到外面:

select sku, catalogname, getdate()
from
(
select sku, catalogname, categoryname, parentOID
from uswebdb.commerce.catalogproducts
union all
select sku, catalogname, categoryname, parentOID
from ukwebdb.commerce.catalogproducts
) F
where (F.CategoryName is not null or F.ParentOID = 113)
and (F.sku not like '%[a-z]%')

您应使用CTRL-L查看查询计划是否不同。可能会有性能影响。

答案 1 :(得分:1)

您提出了一个合理的问题,但首先,让我们澄清术语。 UNIONJOIN是相当不同的操作类型:您使用的第一个(即UNION)将“垂直”合并2个表,而JOIN扩展“水平” 。您的SQL语句似乎是正确的,即使它看起来有点多余(从您的角度来看)。我建议在合并之前过滤掉两个表中的行(完全按照它的实现)。唯一值得尝试的修改是使用UNION代替UNION ALL(无重复)。