是否有人知道如何编写查询以使所需结果与此数据库中的工具/升降计划/ cranimax相似
resource_category_id category_name parent_category
1 Tools 0
2 product literature 0
3 Terms and Conitions 0
4 crane library 1
5 geniune 1
6 lift planning 1
8 cranimax 6
为此,我写了一个这样的查询,但是没有完成,例如,如果我从cranimax
中选择它有一个parent_category 6
,那么这就是我的想法,所以它应该与那行有resource_category_id,那行有parent_category 1
,它应该重复,直到父类别0出现。
$data['breadcrumbs'] = $this->Manito_model->get_breadcrumbs_details($resource_id);
public function get_breadcrumbs_details($resource_id)
{
$query=$this->db->query("select * from resource_category as m WHERE m.resource_category_id = $resource_id union (select * from resource_category where parent_category != 0) as m2 on m.parent_category = m2.resource_parent_category");
return $query->result();
}
我希望我的结果像这样
array (size=3)
0 =>
object(stdClass)[35]
public 'resource_category_id' => string '8' (length=1)
public 'category_name' => string 'cranimax' (length=8)
public 'parent_category' => string '6' (length=1)
public 'created_at' => string '2017-11-04 13:59:39' (length=19)
1 =>
object(stdClass)[35]
public 'resource_category_id' => string '6' (length=1)
public 'category_name' => string 'lift planning' (length=8)
public 'parent_category' => string '1' (length=1)
public 'created_at' => string '2017-11-04 13:59:39' (length=19)
2 =>
object(stdClass)[35]
public 'resource_category_id' => string '1' (length=1)
public 'category_name' => string 'Tools' (length=8)
public 'parent_category' => string '0' (length=1)
public 'created_at' => string '2017-11-04 13:59:39' (length=19)
答案 0 :(得分:0)
UNION用于将多个SELECT语句的结果合并到一个结果集中(即使它变得非常简单:你需要做两个选择,但你只需要一个结果,然后你就建立一个联合) 在你的情况下,你不需要UNION,而是一个简单的JOIN,用其他数据“完成”你的结果:
select m.*, m2.category_name AS parent_name FROM resource_category AS m LEFT JOIN resource_category m2 ON m2.resource_category_id = m.resource_parent_category WHERE m.resource_category_id = $resource_id