SQL表排序非规范化表

时间:2013-01-23 09:27:16

标签: sql sorting

我有两张桌子:

“产品”包含基本产品数据

product_id | product_name | product_picture
1          | test         | pic.jpg
2          | samp         | sam.gif

product_details包含产品的详细信息(每个product_id 1个或更多)

product_id | unit   | value
1          | size   | 100mm
1          | weight | 100g
2          | size   | 80mm
2          | color  | red

现在我想按大小排序。 (有点像正常的表)结果:

2 | sample | sam.gif | size | 80mm  | color  | red
1 | test   | pic.jpg | size | 100mm | weight | 100g

编程语言是PHP。 Usualy我会这样做(PSEUDOCODE):

while (SELECT * FROM a) {
   while(SELECT * FROM b WHERE id = a.id) {
      myarray[a.id][b.unit] = b.value;
   }
}

但我不知道如何对结果进行排序。 (我想用PHP进行排序的性能不如SQL?)

编辑: 新想法:首先执行查询以正确的顺序选择product_ids:

while(SELECT products_id FROM products INNER JOIN products_details USING(products_id) WHERE unit = 'size' ORDER BY value) {
   while( SELECT value, unit FROM products_details WHERE products_id = id) {
      myarray[a.id][b.unit] = b.value;
   }
}

1 个答案:

答案 0 :(得分:2)

如果要对其进行规范化,则应在不同列中具有不同类型的属性。基本上,您需要取消您的属性。一种方法是使用条件聚合,如下所示:

SELECT
  p.product_id,
  p.product_name,
  p.product_picture,
  MAX(CASE d.unit WHEN 'size'   THEN d.value END) AS size,
  MAX(CASE d.unit WHEN 'weight' THEN d.value END) AS weight,
  MAX(CASE d.unit WHEN 'color'  THEN d.value END) AS color
FROM products p
LEFT JOIN product_details d
ON p.product_id = d.product_id
GROUP BY
  p.product_id,
  p.product_name,
  p.product_picture
;

这将为您提供如下数据集:

product_id  product_name  product_picture  size   weight  color
----------  ------------  ---------------  -----  ------  -----
1           test          pic.jpg          100mm  100g    NULL
2           samp          sam.gif          80mm   NULL    red

为每个属性分配一个单独的列后,您可以按照自己喜欢的方式对行进行排序。例如:

SELECT
  p.product_id,
  p.product_name,
  p.product_picture,
  MAX(CASE d.unit WHEN 'size'   THEN d.value END) AS size,
  MAX(CASE d.unit WHEN 'weight' THEN d.value END) AS weight,
  MAX(CASE d.unit WHEN 'color'  THEN d.value END) AS color
FROM products p
LEFT JOIN product_details d
ON p.product_id = d.product_id
GROUP BY
  p.product_id,
  p.product_name,
  p.product_picture
ORDER BY
  weight,
  color,
  size
;