简体   繁体   中英

Combining 2 sql queries in codeigniter

I have two tables. voting_ip and country . I want to retrieve results from country table where open_id_fk ( foreign key ) of voting_ip table is equal to open_id ( Primary Key ) of country table. How to write sql query to combine these queries and return the result. I am using the below code in my codeigniter model to retrieve number of occurances of open_id_fk in voting_ip table.

public function mostvotedans()
{
    $this->db->select('open_id_fk, COUNT(*) as total');
    $this->db->group_by('open_id_fk'); 
    $this->db->order_by('total', 'desc'); 
    $query = $this->db->get('voting_ip', 5);
    return $query;

    $query = $this->db->query("SELECT * FROM country WHERE open_id_fk=open_id;");  
    return $query;         
}

Use a join statement :

$query = $this->db->select('v.open_id_fk, COUNT(v.*) AS total, c.country_name')
            ->join('country AS c', 'c.open_id = v.open_id_fk')
            ->from('voting_ip AS v')
            ->group_by('v.open_id_fk')
            ->order_by('total', 'DESC')
            ->limit(5);

Should work, I put 'country_name' because I don't know your tables.

change it as following.

  public function mostvotedans()
{
  $this->db->select('c.open_id,COUNT(ip.open_id_fk) as total')->from('voting_ip ip');
  $this->db->join('country c','c.open_id=ip.open_id_fk');
  $this->db->group_by('ip.open_id_fk'); 
  $this->db->order_by('total', 'desc'); 
  $this->db->limit(5);
 $query = $this->db->get();
 return $query;


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM