mysql | PHP |加入自己的表格

时间:2013-10-25 09:34:04

标签: php mysql codeigniter

我不知道我做对还是错,请不要判断我...... 我想要做的是,如果一条记录属于父级,那么它将与父级ID相关联。让我向您展示下面的表格模式。

enter image description here

我有两列 ItemCategoryID& ItemParentCategoryID

假设ItemCategoryID =4上的记录属于ItemCategoryID =2,则ID 4上的ItemParentCategoryID列将具有ItemCategoryID的ID。

我的意思是在自己的表中有一个循环..

但问题是如何运行选择查询:P 我的意思是向所有父母和孩子展示他们的父母......

5 个答案:

答案 0 :(得分:2)

这通常是一种懒惰的设计选择。理想情况下,您需要一个表格来表示这些关系或/和一定数量的深度。如果parent_id的父级可以拥有它自己的parent_id,则意味着潜​​在的无限深度。

MySQL并不是无限嵌套深度的忠实粉丝。但是php并不介意。在循环中运行多个查询,例如Nil'z的 1 ,或者考虑获取所有行并在php中的数组中对它们进行排序。如果您几乎总是获取所有行,那么最后的解决方案就很好了,从而使MySQL过滤变得过时。

最后,考虑一下您是否可以在数据库结构中采用更理想的方法。不要害怕为此使用多张桌子。

  1. 这可能是未来强大的表现小偷。每次加载页面时,无法控制的mysql查询数量很容易失控。

答案 1 :(得分:0)

我认为您不希望/可以在查询中执行此操作,因为您可以很长时间地嵌套。

您应该创建一个在检索类别时调用自身的getChilds函数。这样你可以嵌套超过2个级别。

function getCategory()
{
   // Retrieve the category


   // Get childs
   $childs = $this->getCategoryByParent($categoryId);
}

function getCategorysByParent($parentId)
{
  // Get category

  // Get childs again.
}

答案 2 :(得分:0)

试试这个:

function all_categories(){
    $data   = array();
    $first  = $this->db->select('itemParentCategoryId')->group_by('itemParentCategoryId')->get('table')->result_array();
    if( isset( $first ) && is_array( $first ) && count( $first ) > 0 ){
        foreach( $first as $key => $each ){
            $second = $this->db->select('itemCategoryId, categoryName')->where_in('itemParentCategoryId', $each['itemParentCategoryId'])->get('table')->result_array();

            $data[$key]['itemParentCategoryId'] = $each['itemParentCategoryId'];
            $data[$key]['subs']                 = $second;
        }
    }
    print_r( $data );
}

答案 3 :(得分:0)

MySQL不支持递归查询。可以通过recursive calls to a stored procedure模拟递归查询,但这是hackish和次优。

other ways to organise your data,这些结构允许非常有效的查询。

答案 4 :(得分:0)

这个问题常常出现,我甚至不愿意抱怨您无法使用Google或SO搜索,或提供冗长的解释。

此处 - 使用我创建的这个库:http://codebyjeff.com/blog/2012/10/nested-data-with-mahana-hierarchy-library,这样您就不会关闭数据库