Zend_Db加入查询

时间:2014-03-25 11:39:18

标签: database zend-framework

我正在尝试在Zend_Db中对3个表应用连接查询。我的查询如下:

$id_array = array("1","2");

$query = $this->select();
$query->from(array('b' => 'brands'), array('b.brand_id','b.brand_name'))->where('b.brand_id NOT in (?)', $id_array)->order('RAND()')->limit(5);
$query->join(array('p' => 'product'), 'b.brand_id = p.brand_id', array('p.product_id', 'p.product_price'));
$query->join(array('pimg' => 'product_img_map'), 'p.product_id = pimg.product_id', array('pimg.img_location'));
$query->setIntegrityCheck(false);
$resultRows = $this->fetchAll($query);
return $resultRows; 

在一个品牌中可能有多个产品,但在查询中我对品牌表应用限制即5.默认情况下它也适用于产品也是因为如果一个品牌有5个产品它只提供一个品牌的信息对此我有任何建议吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来获得所需的结果:

$id_array = array("1","2");

$subQuery = $this->select()
    ->from(array('b' => 'brands'), array('b.brand_id','b.brand_name'))
    ->where('b.brand_id NOT in (?)', $id_array)
    ->order('RAND()')
    ->limit(5);
$query = $this->select()
    ->from(array('b' => $subQuery), array('*'))
    ->join(array('p' => 'product'), 'b.brand_id = p.brand_id', array('p.product_id', 'p.product_price'))
    ->join(array('pimg' => 'product_img_map'), 'p.product_id = pimg.product_id', array('pimg.img_location'));