我有 2 个表我希望尽可能有效地“加入”。
第一个表有一个产品代码,我需要这个表中的所有列。
2nd 包含相同的产品代码,每个产品代码具有多行。
我需要获取产品代码与第一个表匹配的第二个表行的最小值和最大值。
以下是我到目前为止所拥有的,它很丑陋,可能非常不正确和缓慢。第二个表是问题,因为它有 750k 行!
ALTER PROCEDURE [dbo].[GetProductDescriptions]
(
@site INT = 0,
@langid INT = 0
)
AS
select p.* ,
stuff((select ',' + cast(FilterValueID as nvarchar(max))from Product_Filter_Mapping c where c.ProductCode = p.ProductCode AND c.ApplicationID = @site for xml path('')),1,1,'') as FilterIDs,
stuff((select ',' + cast(BrandID as nvarchar(max))from Product_Brand_Mapping d where d.ProductCode = p.ProductCode AND d.ApplicationID = @site for xml path('')),1,1,'') as BrandIDs,
stuff((select '|' + cast(Name as nvarchar(max))from Brands e where e.ID IN (SELECT BrandID FROM Product_Brand_Mapping f WHERE f.ProductCode = p.ProductCode AND f.ApplicationID = @site) for xml path('')),1,1,'') as BrandNames,
stuff((select ',' + cast(DepartmentID as nvarchar(max))from Product_Department_Mapping e where e.ProductCode = p.ProductCode and e.ApplicationID = @site for xml path('')),1,1,'') as DepartmentIDs,
(select MAX(pr.Sell) from Products pr where pr.ProductCode = p.ProductCode AND pr.ApplicationID = @site) as SellTo,
(select MAX(pr.WholeSale) from Products pr where pr.ProductCode = p.ProductCode AND pr.ApplicationID = @site) as WasTo
from ProductDescription p WHERE p.ApplicationID = @site AND p.LanguageID = @langid