【问题标题】:Select from the result of the same query从同一查询的结果中选择
【发布时间】:2011-11-10 17:28:57
【问题描述】:

我有一张看起来像这样的表:

id  parent_id    name
1   0            page #1
2   1            Page #2
3   1            Page #3
4   2            Page #4

*parent_id* 关联到 id。

第 4 页是第 2 页的子页 并且页面 #2 是页面 #1 的子页面 第 3 页也是如此。

我需要一个 mysql 查询,它可以让所有孩子都进入,比如 id 1。 这将返回所有这些页面,因为所有页面“主父”(大声笑)都是页面 #1。

【问题讨论】:

标签: mysql


【解决方案1】:

你基本上有两种选择:

  • 在您的应用程序逻辑或查询中使用递归(如果您的 RDBMS 支持)

  • 存储树中每个节点的左/右值,让您轻松找到节点的所有子树

这两个选项都包含在 sitepoint 的一篇优秀文章中,http://www.sitepoint.com/hierarchical-data-database/(但它不包括 RDBMS 递归,你可能不支持它)

【讨论】:

    【解决方案2】:

    我以为我只是为这个问题留下一个解决方案。不仅在 mysql 中,而且在 php 中。

    这是一个调用自身来检查当前页面(在循环中)是否有子页面的函数。 它将返回一个包含所有子(包括父)ID 的数组。

    public function getPageChildren($parent_id) {
        $result = mysqli_query($con, 'SELECT id FROM pages WHERE parent_id = '.$parent_id);
        while($children = mysqli_fetch_assoc($result)) {
            if($children) {
                $childrenArray[] = $children['id'];
                $childrensChildren = getPageChildren($children['id']);
    
                foreach($childrensChildren as $childrensChild) {
                    $childrenArray[] = $childrensChild;
                }
            }
        }
        return $childrenArray;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-03
      • 2012-11-30
      • 1970-01-01
      • 2010-10-18
      • 2016-11-14
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多