CodeIgniter:如何执行选择(不同的字段名称)MySQL查询

时间:2009-03-18 01:07:00

标签: php mysql codeigniter distinct

我正在尝试检索字段中所有唯一值的计数。

示例SQL:

SELECT count(distinct accessid) FROM (`accesslog`) WHERE record = '123'

如何在CodeIgniter中进行此类查询?

我知道我可以使用$this->db->query(),并编写自己的SQL查询,但我还有其他要求,我想使用$this->db->where()。如果我使用->query(),我必须自己编写整个查询。

5 个答案:

答案 0 :(得分:94)

$record = '123';

$this->db->distinct();

$this->db->select('accessid');

$this->db->where('record', $record); 

$query = $this->db->get('accesslog');

然后

$query->num_rows();

应该走很长的路。

答案 1 :(得分:10)

使用以下代码

进行试用
function fun1()  
{  
   $this->db->select('count(DISTINCT(accessid))');  
   $this->db->from('accesslog');  
   $this->db->where('record =','123');  
   $query=$this->db->get();  
   return $query->num_rows();  
}

答案 2 :(得分:10)

您还可以运行 - >选择(' DISTINCT`field`',FALSE),第二个参数告诉CI不要转义第一个参数。使用第二个参数,输出将是 SELECT DISTINCT`field` ,而不是没有第二个参数, SELECT`DISTINCT``field`

答案 3 :(得分:1)

由于计数是预期的最终值,因此在您的查询传递中

$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record); 
$query = $this->db->get()->result_array();
return count($query);

计数重新调整的值

答案 4 :(得分:1)

简单但有用的方法:

$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
        return $query;
相关问题