关联sql查询

时间:2017-08-10 12:40:16

标签: sql tsql join

嗨我有一个查询问题加入递归。我不明白我如何通过表OS_Product_Category_Mapping将类别级别的每个字段作为我的产品的category_id。我的疑问是:

    SELECT pr.Id, pr.Name, pr.Sku, ct.category_l2_id, ct.category_l2_name,   
         ct.category_l1_id, ct.category_l1_name, ct.category_l0_id,   
      ct.category_l0_name
    FROM PSV_STG.dbo.OS_Product  as pr
        left join  PSV_STG.dbo.OS_Product_Category_Mapping as prcat 
        on prcat.ProductId =pr.Id
          left join (
          select t1.[Id] category_l2_id,t1.[Name] category_l2_name,t2.Id  
          category_l1_id,t2.Name category_l1_name,t2.ParentCategoryId   
          category_l0_id,t3.Name category_l0_name
             from [PSV_STG].dbo.OS_Category t1
          join (SELECT distinct [Id],[Name],[ParentCategoryId]
             FROM [PSV_STG].dbo.OS_Category 
          where [ParentCategoryId]=(select [Id] 
                from [PSV_STG].dbo.OS_Category
          where [Name]='Каталог' and Deleted=0)) t2 
              on t1.[ParentCategoryId]=t2.Id
            join (select [Id],[Name]
           from [PSV_STG].dbo.OS_Category
          where [Name]='Каталог' and Deleted=0) t3
              on t2.[ParentCategoryId]=t3.Id
          where t1.Deleted=0 and t1.Published=1 ) as ct
        on ct.category_l0_id  = prcat.CategoryId or  ct.category_l1_id =             prcat.CategoryId or ct.category_l2_id = prcat.CategoryId

输出我有2000条记录而不是300条。我必须联系ct             在ct.category_l0_id = prcat.CategoryId或ct.category_l1_id = prcat.CategoryId或ct.category_l2_id = prcat.CategoryId

但另一种方式。

我必须将我的递归的每个级别与产品联系起来。这个查询不对。我不知道如何在递归内的ct.category_l0_id = prcat.CategoryId或ct.category_l1_id = prcat.CategoryId或ct.category_l2_id = prcat.CategoryId上制作此ct

0 个答案:

没有答案