Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在codeigniter中组合2个sql查询_Php_Mysql_Sql_Codeigniter_Model View Controller - Fatal编程技术网

Php 在codeigniter中组合2个sql查询

Php 在codeigniter中组合2个sql查询,php,mysql,sql,codeigniter,model-view-controller,Php,Mysql,Sql,Codeigniter,Model View Controller,我有两张桌子投票_ip和国家/地区。我想从country表中检索结果,其中voting\u ip表的open\u id\u fk(外键)等于country表的open\u id(主键)。如何编写sql查询来组合这些查询并返回结果。我在我的codeigniter模型中使用以下代码来检索投票ip表中的open\u id\u fk发生次数 public function mostvotedans() { $this->db->select('open_id_fk, COUNT(*)

我有两张桌子<代码>投票_ip和
国家/地区
。我想从
country
表中检索结果,其中
voting\u ip
表的
open\u id\u fk
(外键)等于
country
表的
open\u id
(主键)。如何编写sql查询来组合这些查询并返回结果。我在我的codeigniter模型中使用以下代码来检索
投票ip
表中的
open\u id\u 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;         
}
使用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\u 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;


}
谢谢你。。这奏效了:)太棒了。。我只是对它进行了修改,使所有列都变成$此->数据库->选择('c.*,将(ip.open\u id\u fk)计数为总数)->来自('voting\u ip');