【问题标题】:CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL QueryCodeIgniter:如何进行选择(不同的字段名)MySQL 查询
【发布时间】:2010-10-13 23:39:40
【问题描述】:
我正在尝试检索字段中所有唯一值的计数。
示例 SQL:
SELECT count(distinct accessid) FROM (`accesslog`) WHERE record = '123'
如何在 CodeIgniter 中进行这种查询?
我知道我可以使用$this->db->query(),并编写自己的 SQL 查询,但我还有其他需要使用$this->db->where()。如果我使用->query(),尽管我必须自己编写整个查询。
【问题讨论】:
标签:
php
mysql
codeigniter
distinct
【解决方案1】:
$record = '123';
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get('accesslog');
然后
$query->num_rows();
应该有很长的路要走。
【解决方案2】:
用下面的代码试试
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();
}
【解决方案3】:
你也可以运行->select('DISTINCT `field`', FALSE),第二个参数告诉CI不要转义第一个参数。
第二个参数为false,输出将是SELECT DISTINCT `field`,而不是没有第二个参数SELECT `DISTINCT` `field`
【解决方案4】:
简单但有用的方法:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;
【解决方案5】:
由于计数是预期的最终值,因此在您的查询过程中
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
返回值的计数