2011-03-17 89 views
1

我有需要进行重构一个SQL查询。基本上查询获取指定客户订购的所有产品类型。问题是结果是以列而不是行返回的。这需要改变另一种方式来使查询更通用。重构SQL查询返回的结果为行,而不是列

原来这就是该查询返回:

Name ProductType1 ProductType2 ProductType3 
-------------------------------------------------- 
Marc PT09   P15   PT33 

,这是它应该是什么:

Name ProductType 
---------------- 
Marc PT09 
Marc P15 
Marc PT33 

这是我已经简化了一下查询:

SELECT 
     CustomerData.Name as Name 
     Product1.productType as ProductType1, 
     Product2.productType as ProductType2, 
     Product3.productType as ProductType3 
FROM 
    (SELECT ProductID, Name 
      FROM 
       Customer 
       Orders 
     WHERE Customer.ID = 111 
    ) as CustomerData 

LEFT JOIN (SELECT DISTINCT CP.ProductID as ProductID, 
          PC.Type as ProductType 
      FROM 
       CustomerProduct CP, 
       ProductCategory PC 
      WHERE 
       PC.Category = 'A' 
       AND CP.ProductCategoryID = PC.ID 
      ) as Product1 
      on CustomerData.ProductID = Product1.ProductID 

LEFT JOIN (SELECT DISTINCT CP.ProductID as ProductID, 
          PC.Type as ProductType 
      FROM 
       CustomerProduct CP, 
       ProductCategory PC 
      WHERE 
       PC.Category = 'B' 
       AND CP.ProductCategoryID = PC.ID 
      ) as Product2 
      on CustomerData.ProductID = Product1.ProductID 

LEFT JOIN (SELECT DISTINCT CP.ProductID as ProductID, 
          PC.Type as ProductType 
      FROM 
       CustomerProduct CP, 
       ProductCategory PC 
      WHERE 
       PC.Category = 'C' 
       AND CP.ProductCategoryID = PC.ID 
      ) as Product3 
      on CustomerData.ProductID = Product1.ProductID 

所以我一直在想分裂加入到一个单独的存储过程,然后再调用这个,因为我需要更多的productTypes,但我似乎无法得到这个工作。任何人有关如何使这项工作的想法?

+0

在你面前已知产品类型的数量正在执行的查询?如果是这样,您可以动态创建具有多个UNION的SQL。 – 2011-03-17 10:55:20

回答

3

在做的事情列实际上通常要困难得多。

假设规范化的表客户,产品和订单,你不需要做任何事情不仅仅是:

SELECT C.customer_name 
    , P.product_type 
FROM Customers C 
    JOIN Orders O 
    ON O.customer_id=C.customer_id 
    JOIN Products P 
    ON O.product_id=P.product_id 
WHERE C.ID = 111 

如果这不起作用,请列出涉及的表的结构。

+1

+1是的,就是这样做的。它可能只需要'LEFT JOIN'而不是'JOIN',这取决于他的数据和他想表现的内容。或者,也许一个'GROUP BY'如果客户有相同产品的不少订单,你只是希望看到一个行任何的(订单)的。或者如果他想要在ProductCategory上显示或过滤,也可以再加入一次。但这是要走的路。再加上查询看起来简单而优雅:少于10行代码而不是40+复杂的4行子查询。 – 2011-03-17 11:13:40

0

我会假设你的表看起来像这样

客户

id | name 
11 | Marc 

产品

id | type 
21 | PT09 
22 | P15 
23 | PT33 

订单

id | id_customer | id_product | quantity 
31 | 11   | 21   | 4 
32 | 11   | 22   | 6 
33 | 11   | 23   | 8 

那么你的查询

SELECT 
    a.name, 
    c.type 
FROM 
    Customer a 
LEFT JOIN 
    Orders b ON b.id_customer = a.id 
LEFT JOIN 
    Products c ON c.id = b.id_product