2011-11-03 69 views
0

如何在Zend Framework中執行此sql查詢,我需要在PDO上下文中如何執行此操作?我試過 - >查詢,但不知道我是否得到這個權利。這三個變量是user_id和來自日期。如何在Zend中執行此sql查詢?

SELECT 
ss.subcategory_id, 
ss.subcategory_name, 
ss.subcategory_issaving, 
IFNULL(SUM(m.mv_monthly_total),0) AS expendsum 
FROM 
(SELECT 
    s.subcategory_id, 
    s.subcategory_name, 
    s.subcategory_issaving 
FROM 
    subcategory s 
    WHERE 
    s.subcategory_isexpend = 'Y' 
    AND 
    s.subcategory_issaving = 'Y') ss 
LEFT JOIN 
    mv_monthly m 
ON ss.subcategory_id = m.mv_monthly_subcategory_id 
AND m.mv_monthly_user_id = 2 
AND m.mv_monthly_month >= '2010-01-01' 
AND m.mv_monthly_month <= '2020-01-01' 
GROUP BY 
ss.subcategory_id, 
ss.subcategory_name, 
ss.subcategory_issaving 
ORDER BY 
ss.subcategory_issaving DESC, 
expendsum; 

我都試過,沒有運氣

$db = Zend_Db_Table::getDefaultAdapter(); 
    $dbExpr1 = new Zend_Db_Expr("s.subcategory_id, s.subcategory_name, s.subcategory_issaving"); 
    $dbExpr2 = new Zend_Db_Expr("ss.subcategory_id, ss.subcategory_name, ss.subcategory_issaving, IFNULL(SUM(m.mv_monthly_total),0) AS expendsum"); 
    $select = $db->select() 
     ->from(
      array(
       'ss' => new Zend_Db_Expr(
        '('. $db->select() 
         ->from(array("s" => "subcategory"), $dbExpr1) 
         ->where("s.subcategory_isexpend = 'Y'") 
         ->where("s.subcategory_issaving = 'Y'") .')' 
       ) 
      ), 
      $dbExpr2 
     ) 
     ->joinLeft(array("m" => "mv_monthly"), "ss.subcategory_id = m.mv_monthly_subcategory_id") 
     ->where("m.mv_monthly_user_id = ?", $user_id)  
     ->where("m.mv_monthly_month >= ?", $fromMonth) 
     ->where("m.mv_monthly_month <= ?", $toMonth) 
     ->group(array("ss.subcategory_id","ss.subcategory_name","ss.subcategory_issaving")) 
     ->order(array("ss.subcategory_issaving DESC", "expendsum")); 
    $row = $db->fetchAll($select); 
+1

我認爲你必須開始認真考慮使用的意見。 –

+0

不幸的是,對我們來說這不是一種選擇。 – user611468

回答

0

對於這樣一個複雜的查詢下,你可以執行它,而不是直接使用面向對象的方法,因爲它會與像查詢相當複雜那。

嘗試這樣的事情,與你的替代我的查詢,並結合到查詢您的變量:

$db = Zend_Db_Table::getDefaultAdapter(); 
    $stmt = new Zend_Db_Statement_Pdo($db, 'SELECT a, b, c FROM a WHERE username = ? AND date = ?'); 

    try { 
     $res = $stmt->execute(array($user_id, $fromMonth)); 

     if ($res) { 
      $rows = $stmt->fetchAll(); 
     } 
    } catch (Zend_Db_Statement_Exception $dbex) { 
     // log Query failed with exception $dbex->getMessage(); 
    } 

如果你喜歡使用面向對象的方法,或者需要,因爲查詢的某些部分會是有條件的,我通常先通過子查詢構建自己的select,然後用子查詢的select對象將其嵌入到主查詢中。

這裏是我的意思了:

$subselect = $this->getDbTable() 
         ->select() 
         ->from('mytable', array('time' => 'max(time)', 'id')) 
         ->where('id IN (?)', $serialNumbers) 
         ->group('id'); 

    $select = $this->getDbTable() 
         ->select() 
         ->setIntegrityCheck(false) 
         ->from('mytable') 
         ->join('other', 'mytable.id = other.id', array('label')) 
         ->join(array('dt' => $subselect), 
          '(mytable.time, mytable.id) = (dt.time, dt.id)', '');