Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.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
Sql 如何使用codeigniter通过group by获取所有行_Sql_Codeigniter - Fatal编程技术网

Sql 如何使用codeigniter通过group by获取所有行

Sql 如何使用codeigniter通过group by获取所有行,sql,codeigniter,Sql,Codeigniter,我有一个表格来管理视频列表的投票,我需要获得单个条目的投票数 这是我的桌子: id | user_id | entry_id | vote 这是一个条目示例: 1 | 1 | 729 | 3 2 | 2 | 729 | 4 3 | 3 | 729 | 4 4 | 4 | 729 | 1 5 | 5 | 729 | 4 我需要得到有多少用户投票1、3和4,以及投票该条目的总用户数

我有一个表格来管理视频列表的投票,我需要获得单个条目的投票数

这是我的桌子:

id | user_id | entry_id | vote
这是一个条目示例:

1  |    1  |    729  |  3  
2  |    2  |    729  |  4  
3  |    3  |    729  |  4  
4  |    4  |    729  |  1  
5  |    5  |    729  |  4
我需要得到有多少用户投票1、3和4,以及投票该条目的总用户数

在这种情况下,我应该得到:

Users that voted 1: 1  
Users that voted 3: 1  
Users that voted 4: 3  
Total user: 5
在这种情况下,我可以用php创建百分比

这就是我对活动记录所做的:

$this->db->select('COUNT(*) as tot_users, vote', FALSE);
$this->db->from('voti_video');
$this->db->where('entry_id', $id_entry);
$this->db->group_by('vote');
通过这段代码,我可以准确地得到用户投票的内容以及他们中有多少人投票。
现在如何在不进行新查询的情况下获取用户总数?

有可能吗?

您需要在选择列表中有一个子查询,为您提供总行数

$this->db->select('count(*)'); 
$this->db->from('voti_video');

// Render the subquery to a string 
$subQuery = $this->db->compileselect();

// Reset active record 
$this->db->resetselect();

// Generate the main query as posted by you and include the subquery 

$this->db->select('COUNT(*) as tot_users, vote', FALSE);
$this->db->select("($subQuery) as TotalVotes");
$this->db->from('voti_video');
$this->db->where('entry_id', $id_entry);
$this->db->group_by('vote');

请尝点类似的

$query = $this->db->query("
            select count(*) total,
                sum(case when entry_id = '".$id_entry."' then 1 else 0 end) tot_users,
            from voti_video
            group by vote");
从和中窃取的想法。

我使用了此代码

$this->db->select( 'NAME' );
$this->db->select_sum( 'COUNTER' );
$this->db->from( 'TABLE' );
$this->db->order_by( 'NAME', 'ASC');
$this->db->group_by( 'NAME' );
$this->db->limit( 5 );
$result = $this->db->get();
return ( $result->num_rows() > 0 ? $result->result_array() : false );

我在
compileselect
上遇到一个致命错误,它似乎已从Corenop中删除,sum()末尾的查询中有一个错误,您不需要
。顺便说一下,在上面的例子中,我得到了这样一个结果:这与我的输出相同,但我没有用户总数