在codeigniter中组合2个sql查询


Combining 2 sql queries in codeigniter

我有两个表。voting_ipcountry。我想从country表检索结果,其中voting_ip表的open_id_fk (外键)等于country表的open_id (主键)。如何编写sql查询来组合这些查询并返回结果。我在我的codeigniter模型中使用以下代码来检索voting_ip表中open_id_fk的出现次数。

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;         
}

修改如下:

  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;

}

使用join语句:

$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);

应该可以,我放了'country_name'因为我不知道你的表