SQL子查询在结果中查找类别

问题描述:

I am getting some data from my database table. The query I use is very simple

$query = $this->db->query("SELECT * 
                                FROM mc_boxes_has_categories 
                                WHERE mc_boxes_idmc_boxes = $box_id
                              ");
    $categories = $query->result_array();
    return $categories; 

The output of this query is a s follows

Array
(
[0] => Array
    (
        [mc_boxes_idmc_boxes] => 12
        [categories_idcategories] => 1
    )

[1] => Array
    (
        [mc_boxes_idmc_boxes] => 12
        [categories_idcategories] => 4
    )

[2] => Array
    (
        [mc_boxes_idmc_boxes] => 12
        [categories_idcategories] => 5
    )

)

My question is how can I check if the categories contain category id 1 then render 1 view and if it does not contain then render another view. I need to check for category id 1 somehow is it possible in sql ?

Thanks

If you want select only those categories which has category 1 change your select query as below:

$query = $this->db->query("SELECT * 
                                FROM mc_boxes_has_categories 
                                WHERE mc_boxes_idmc_boxes = $box_id AND   categories_idcategories = 1
                              ");

And if you want select all categories and then do some different with id 1 categories do this:

foreaach($categories as $category)
{
   if($category['categories_idcategories'] == 1)
   {
       // render view 1  
   }
   else
   {
       // render another view
   }
}

You could iterate and group

foreach($categories as $row){
    $categories[$row['categories_idcategories']][] = $row['mc_boxes_idmc_boxes'];
}

// whatever compare logic you need
if(isset($categories[1][0])){

}