2013-11-01 41 views
0

嗨,我有麻煩與此查詢如何建立嵌套選擇在Zend的分貝

SELECT * FROM(
    SELECT `b`.*,`owner`.firstname,`owner`.lastname,`owner`.email, 
    (
     SELECT COUNT(`ps`.profile_id) FROM `profile` AS `ps` 
     LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id 
     WHERE `xbp`.brand_id = b.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL 
    ) AS `salesrepTotal`, 
    (
     SELECT GROUP_CONCAT(`ms`.firstname) FROM `profile` AS `ps` 
     LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id 
     LEFT JOIN `member` AS `ms`ON `ms`.member_id = `ps`.member_id 
     WHERE `xbp`.brand_id = `b`.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL 
    ) AS `salesrep`, 
    (
     SELECT COUNT(`s`.store_id) FROM `store` AS `s` 
     LEFT JOIN `xref_store_profile_brand` AS `xbs` ON `xbs`.store_id = `s`.store_id 
     WHERE `xbs`.brand_id = `b`.brand_id AND `xbs`.brand_id IS NOT NULL 
    ) AS `storeTotal`, 
    (
     SELECT GROUP_CONCAT(`s`.name) FROM `store` AS `s` 
     LEFT JOIN `xref_store_profile_brand` AS `xbs` ON `xbs`.store_id = `s`.store_id 
     WHERE `xbs`.brand_id = `b`.brand_id AND `xbs`.brand_id IS NOT NULL 
    ) AS `store` 

    FROM `brand` AS `b` 
    LEFT JOIN 
    (
     SELECT `m`.firstname,`m`.lastname,`m`.email,`xspb`.brand_id FROM `member` AS `m` 
     LEFT JOIN `profile` as `p` ON `p`.member_id = `m`.member_id AND `p`.role = 'designer' AND `p`.isPrimary = 1 
     LEFT JOIN `xref_store_profile_brand` AS `xspb` ON `xspb`.profile_id = `p`.profile_id AND `xspb`.store_id IS NULL 
    ) AS `owner` ON `owner`.brand_id =`b`.brand_id 

    GROUP BY `b`.brand_id 
) AS `final` 

我如何轉換這對Zend_Db_Select對象的對象?

釷的主要問題是 這部分

SELECT `b`.*,`owner`.firstname,`owner`.lastname,`owner`.email, 
    (
     SELECT COUNT(`ps`.profile_id) FROM `profile` AS `ps` 
     LEFT JOIN `xref_store_profile_brand` AS `xbp` ON `xbp`.profile_id = `ps`.profile_id 
     WHERE `xbp`.brand_id = b.brand_id AND ps.role = 'salesrep' AND `xbp`.store_id IS NULL 
    ) AS `salesrepTotal`, 
+0

可能重複http://stackoverflow.com/questions/1718888/zend-db-table-subquery ) – Ankur

回答

1

您需要在您的查詢,array structures for select AS使用Zend_Db_Expr對象。

下面

纔是解決您正在尋找:

<?php 

$db = Zend_Db_Table::getDefaultAdapter(); 

// inner query 
$sqlSalesRepTotal = $db->select() 
     ->from(array('ps' => 'profile')) 
     ->joinLeft(array('xbp' => 'xref_store_profile_brand'), 'xbp.profile_id = ps.profile_id') 
     ->where('xbp.brand_id = b.brand_id') 
     ->where('ps.role = ?', 'salesrep') 
     ->where('xbp.store_id IS NULL'); 

// main query 
$sql = $db->select() 
     ->from(array('b' => 'brand'), array(
      // NOTE: have to add parentesis around the expression 
      'salesrepTotal' => new Zend_Db_Expr("($sqlSalesRepTotal)") 
     )) 
     ->where('....') 
     ->group('brand_id'); 


// debug 
var_dump($db->fetchAll($sql)); 
[Zend的\ _db \ _Table子查詢(的