2

我有 2 张桌子:

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

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。通常我会这样做(伪代码):

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;
   }
}
4

1 回答 1

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
;
于 2013-01-25T12:17:00.670 回答