我在两个不同的位置有两个 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 中可能吗?难道是我想太多了?
最佳答案
这些是在不同的服务器上还是不同的数据库上,因为它有很大的不同。您的语法意味着位于同一服务器、不同的数据库上,这意味着您可以将 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 来查看查询计划是否不同。可能会对性能产生影响。
关于sql - 具有相同列和相同 where 子句的两个表的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16472684/