2013-08-26 17 views
1

例如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  | 

我的問題:是否有可用的構建體,它返回一個選擇請求查詢產品1和2在下面的數據結構(或類似)?現在我應該首先運行deveral select請求「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, 
         ), 
        ), 
    ) 
) 
+0

你想獲得產品的嵌套數組,它的屬性數據,就像你的例子?我只是不確定我是否理解你。 – MihanEntalpo

+0

是的,我需要在一個查詢中獲取具有其屬性的多個產品。如果它可行:) – Mindaugas

+0

更好的設計將是如果您保存產品表中的所有屬性... – Justin

回答

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); 
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),以便他們以後仍然可以通過別名引用。