简体   繁体   English

在Codeigniter中合并2个SQL查询

[英]Combining 2 sql queries in codeigniter

I have two tables. 我有两张桌子。 voting_ip and country . voting_ipcountry 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. 我想检索结果country表,其中open_id_fk的( 外键voting_ip表等于open_id的( 主键country表。 How to write sql query to combine these queries and return the result. 如何编写sql查询以组合这些查询并返回结果。 I am using the below code in my codeigniter model to retrieve number of occurances of open_id_fk in voting_ip table. 我在我的codeigniter模型中使用以下代码来检索voting_ip表中open_id_fk出现voting_ip

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. 应该可以,我放了'country_name',因为我不知道你的桌子。

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;


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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