我有一个树形结构表,我的一个表是类别:
category_id | parent_id (in foreign key it is category_id) | title
现在我想要一个查询并给它一个category_id,然后搜索整个表并进入每个孩子并让他们的孩子到达终点并选择所有。
我可以通过PHP实现这一点,但我想看看如何通过SQL实现它,这是我的PHP代码:
function getChild($id){
static $category_ids = [];
$category_ids[] = $id;
$list=$this->_model->select('categories','*', 'category_parent_id = '.$id);
foreach($list as $category) {
$category_ids[] = $category['category_id'];
if($category['last_child'] == 0){
$this->getChild($category['category_id']);
}
}
$category_ids = array_unique($category_ids);
return $category_ids;
}
//$list=$this->_model->select('categories','*', 'parent_id = '.$id);
//The above code is one of my functions (methods) and it select from table category * by parent_id
如何为它编写SQL查询?
哪一个更快(PHP或SQL查询)