2011-02-03 75 views
2

MySQL網站在將分層數據存儲在數據庫中時有一個excellent tutorial。我試圖編寫返回節點的直接子節點的查詢。我不想從MySQL網站複製/粘貼查詢,因爲我試圖以數據庫不可知的方式處理這個問題。如何將複雜的SQL查詢轉換爲Zend_Db_Select語句?

這是我想查詢Zend_Db_Select對象,IFY

SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth 
FROM nested_category AS node, 
    nested_category AS parent, 
    nested_category AS sub_parent, 
    (
     SELECT node.name, (COUNT(parent.name) - 1) AS depth 
     FROM nested_category AS node, 
     nested_category AS parent 
     WHERE node.lft BETWEEN parent.lft AND parent.rgt 
     AND node.name = 'PORTABLE ELECTRONICS' 
     GROUP BY node.name 
     ORDER BY node.lft 
    )AS sub_tree 
WHERE node.lft BETWEEN parent.lft AND parent.rgt 
    AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt 
    AND sub_parent.name = sub_tree.name 
GROUP BY node.name 
ORDER BY node.lft; 
+0

+1僅用於鏈接到教程! – Marcin 2011-02-03 08:37:55

回答

1

您可以嘗試劈裂查詢分爲兩個Zend_Db_Select語句 - 父查詢和子查詢。您可以使用Zend_Db_Select對象from()方法PARAM,象下面這樣:

$mainQuery = $db->select(); 
$mainQuery->from('user'); 

$sub = $db->select(); 
$sub->from('company'); 

$mainQuery->from(array('subquery' => $sub)); 

,你會得到那樣的查詢:

SELECT `user`.*, `sub`.* FROM `user` 
    INNER JOIN (
     SELECT `company`.* FROM `company` 
    ) AS `sub` 

正如你看到的,它會自動將INNER JOIN當你添加第二from() - 但我認爲,可以將您的查詢重寫爲用戶連接,而不是語法上的多重連接。所以你應該使用joinInner()方法,因爲你可以指定連接條件作爲它的第二參數。

注意,子查詢類似於主查詢,所以你可以建立主查詢,複製它的子查詢,並感謝Zend_Db_Select可能性刪除不需要的部分(reset()法)和替換它們:

$mainQuery = $db->select(); //and rest 
$subQuery = clone $mainQuery; 
$subQuery->reset(Zend_Db_Select::WHERE); 
$subQuery->where(); // and add valid conditions for subquery 
+0

+1 - 除了調用`Zend_Db_Adapter_Abstract :: quoteIdentifier`之外,還有更簡單的方法在`from`中指定AS子句嗎? – 2011-02-03 16:16:56

1

你可以直接粘貼在查詢中直接這樣

$result = $db->query("SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth 
     FROM nested_category AS node, 
     nested_category AS parent, 
     nested_category AS sub_parent, 
     (
      SELECT node.name, (COUNT(parent.name) - 1) AS depth 
      FROM nested_category AS node, 
      nested_category AS parent 
      WHERE node.lft BETWEEN parent.lft AND parent.rgt 
      AND node.name = 'PORTABLE ELECTRONICS' 
      GROUP BY node.name 
      ORDER BY node.lft 
     )AS sub_tree 
    WHERE node.lft BETWEEN parent.lft AND parent.rgt 
     AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt 
     AND sub_parent.name = sub_tree.name 
    GROUP BY node.name 
    ORDER BY node.lf"); 

一定要使用quote()輸入任何自己的參數到該查詢。

這是一個作弊,不是我已經採取的行動。