我有 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;
}
}