MySQL在一个查询中选择多个

时间:2013-08-26 12:02:06

标签: php mysql

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

| 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?现在我应首先运行几个选择请求“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,
                        ),
                      ),
    )  
)

2 个答案:

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

答案 1 :(得分: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),以便以后仍然可以通过别名来引用它们。