dongxun5349
dongxun5349
2017-07-19 08:37
浏览 34
已采纳

从具有相同值的列和具有不同值的另一列的多个行中进行选择

I am using codeigniter, i want to select data from a table which has two columns lab_id and service_id

lab_id        service_id
  1              1
  1              2
  3              1

and i only want to select lab_id "1" which has both 1 and 2 as service id. currently i am using following code but not working.

<pre>    
    $this->db->select('lab_id');
    $this->db->from('labs_services_mapping');
    foreach ($data as $value) {
        $this->db->where('service_id',$value['id']);
    }
    $this->db->group_by('lab_id');
    $query = $this->db->get()->result();
</pre>

$data is an array with service_id

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwei1234
    dongwei1234 2017-07-19 08:46
    已采纳

    this should do the trick

    $this->db->select('lab_id');
    $this->db->from('labs_services_mapping');
    foreach ($data as $value) {
        $this->db->or_where('service_id',$value['id']);
    }
    $this->db->group_by('lab_id');
    $query = $this->db->get()->result();
    

    you can try to use where_in too

    $this->db->select('lab_id');
    $this->db->from('labs_services_mapping');
    $this->db->where_in("service_id", $data);
    $this->db->group_by('lab_id');
    $query = $this->db->get()->result();
    

    Since you want a static result you should do this

    $this->db->select('lab_id');
    $this->db->from('labs_services_mapping');
    $this->db->where_in("service_id", [1,2]);
    $this->db->group_by('lab_id');
    $query = $this->db->get()->result();
    
    点赞 评论

相关推荐