簡體   English   中英

在Codeigniter中合並2個SQL查詢

[英]Combining 2 sql queries in codeigniter

我有兩張桌子。 voting_ipcountry 我想檢索結果country表,其中open_id_fk的( 外鍵voting_ip表等於open_id的( 主鍵country表。 如何編寫sql查詢以組合這些查詢並返回結果。 我在我的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;         
}

使用聯接語句:

$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',因為我不知道你的桌子。

如下更改。

  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