MySQL网站提供了有关在数据库中存储层次结构数据的出色教程。我正在尝试编写返回节点的直接子级的查询。我不想仅从MySQL网站复制/粘贴查询,因为我正尝试以与数据库无关的方式来处理此问题。
这是我正在尝试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;
您可以尝试将查询分为两个Zend_Db_Select语句- 父查询和子查询。您可以将Zend_Db_Select对象用作from()方法的参数,如下所示:
Zend_Db_Select
from()
$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()-但我认为,可以将查询重写为用户联接,而不是语法中的multi。因此,您应该使用joinInner()method,因为这样您就可以将连接条件指定为它的第二个参数。
INNER JOIN
joinInner()
注意,该子查询与主查询类似,因此您可以构建主查询,将其克隆为子查询,并且由于Zend_Db_Select可能而删除了不必要的部分(reset()方法)并替换了它们:
reset()
$mainQuery = $db->select(); //and rest $subQuery = clone $mainQuery; $subQuery->reset(Zend_Db_Select::WHERE); $subQuery->where(); // and add valid conditions for subquery