简单的MySql查询单一加入

时间:2014-01-27 00:02:40

标签: php mysql arrays

我需要将2个查询合并到一个联接中,但我的SQL技能并不是最好的。

这是我的疑问:

$query = $this->db->query("
    SELECT p2c.product_id, p.model 
    FROM {$this->prefix}product_to_category p2c 
    LEFT JOIN {$this->prefix}product p 
        ON (p2c.product_id = p.product_id) 
    WHERE p.status < '3' 
    ORDER BY p2c.product_id ASC
");

$products = array();

foreach($query->rows as $product):
    $cats = $this->db->query("
        SELECT category_id 
        FROM {$this->prefix}product_to_category 
        WHERE product_id = '" . (int)$product['product_id'] . "'
    ");

    $categories = array();

    foreach($cats->rows as $category):
        $categories[] = $category['category_id'];
    endforeach;

    $products[$product['model']] = array(
        'product_id' => $product['product_id'],
        'categories' => $categories
    );
endforeach;

return $products;

我需要返回的数组需要如下所示:

[6596-27] => Array
        (
            [product_id] => 243
            [categories] => Array
                (
                    [0] => 7
                    [1] => 88
                )

        )

显然,为更大的单个数组中的每个产品返回此数组。

我确信这可以组合成一个查询,因为第二个查询来自第一个查询表之一,但我无法理解如何在不执行第二个查询的情况下将所有类别都抓到自己的单独数组中

1 个答案:

答案 0 :(得分:1)

这可能是一个解决方案:

$query = $this->db->query("

    SELECT p.product_id, p.model, GROUP_CONCAT(p2c.category_id SEPARATOR ',') as categories
    FROM {$this->prefix}product p
    LEFT JOIN {$this->prefix}product_to_category p2c      
        ON (p.product_id = p2c.product_id ) 
    WHERE p.status < 3
    ORDER BY p2c.product_id ASC GROUP BY p.product_id

");

$products = array();

foreach($query->rows as $product):

    if ( ! array_key_exists($product['model'],$products) ){
      $products[$product['model']] = array()
    }

    array_push( $products[$product['model']],  array(
          'product_id' => $product['product_id'],
          'categories' => explode(',', $product['categories'])
      )
    )

endforeach;

return $products;