重构SQL查询以将结果返回到行而不是列

时间:2011-03-17 10:48:37

标签: sql refactoring

我有一个需要重构的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,但我似乎无法让它工作。任何人都知道如何使这个工作?

2 个答案:

答案 0 :(得分: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 :(得分: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