1

例如我有几张桌子:
产品:

| product_id | name   | price |
| 1          | apple  | 20.32 |
| 2          | pear   | 9.99  |
| 3          | banana | 1.5   |

产品属性:

| attr_id | name   | value |
| 1       | weight | 10 kg |
| 2       | date   | 2013  |
| 3       | color  | red   |

...等等。
最后产品属性关系表:

| product_id | attr_id |
| 1          | 3       |
| 2          | 1       |
| 1          | 2       |
| 3          | 2       |

我的问题:是否有可用的构造 ONE 选择请求查询以以下数据结构(或类似数据结构)返回产品 1 和 2?现在我应该首先运行 deveral 选择请求“where product_id IN (1, 2)”,然后通过循环选择它们的属性。
对不起英语不好:]

array(
    [0] = array(
          product_id = 1,
          name = apple,
          attributes= array(
                        [0] => array(
                           attr_id = 3,
                           name = color,
                           value = red,
                        ),
                        [0] => array(
                           attr_id = 2,
                           name = date,
                           value = 2013,
                        ) 

                      ),
    ),
    [1] = array(
          product_id = 2,
          name = apple,
          attributes= array(
                        [0] => array(
                           attr_id = 1,
                           name = veight,
                           value = 10 kg,
                        ),
                      ),
    )  
)
4

2 回答 2

1

这不仅仅是查询的问题,还有 PHP 代码。这将适合:

$rSelect = mysqli_query('SELECT
     products.id AS record_id,
     products.name AS products_name,
     products.price AS product_price, 
     attributes.id AS attribute_id,
     attributes.name AS attribute_name,
     attributes.value AS attribute_value
   FROM
     products 
     LEFT JOIN products_attributes
       ON products.id=products_attributes.product_id
     LEFT JOIN attributes
       ON products_attributes.attr_id=attributes.id', $rConnect);

$rgResult = [];
while($rgRow = mysqli_fetch_array($rSelect))
{
   $rgResult[$rgRow['record_id']]['product_id']   = $rgRow['record_id'];
   $rgResult[$rgRow['record_id']]['name']         = $rgRow['product_name'];
   $rgResult[$rgRow['record_id']]['price']        = $rgRow['product_price'];
   $rgResult[$rgRow['record_id']]['attributes'][] = [
      'attr_id' => $rgRow['attribute_id'],
      'name'    => $rgRow['attribute_name'],
      'value'   => $rgRow['attribute_value'],
   ];
};
//var_dump($rgResult);
于 2013-08-26T12:16:14.510 回答
0

您正在寻找的查询是:

select
    p.product_id,
    p.name as product_name,
    a.attr_id,
    a.name as attr_name,
    a.value
from
    products as p
    inner join `product-attribute` as pa on p.id = pa.product_id
    inner join attribute as a on pa.attr_id = a.attr_id

这将返回一个简单的结果表,您可以从中创建多维数组。

您可能会在此查询中注意到两件事:

  • `我在表名周围使用反引号,product-attribute因为它-在名称中包含一个破折号,这是保留的。所以你需要通过把它放在反引号中来逃避这个名字。
  • 因为字段名称name不明确,所以我给它们一个别名 ( product_name/ attr_name),以便以后仍然可以通过别名引用它们。
于 2013-08-26T12:22:55.330 回答