php CodeIgniter:如何执行选择(不同字段名)MySQL 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/656622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query
提问by Ian
I'm trying to retrieve a count of all unique values in a field.
我正在尝试检索字段中所有唯一值的计数。
Example SQL:
示例 SQL:
SELECT count(distinct accessid) FROM (`accesslog`) WHERE record = '123'
How can I do this kind of query inside of CodeIgniter?
如何在 CodeIgniter 中执行此类查询?
I know I can use $this->db->query(), and write my own SQL query, but I have other requirements that I want to use $this->db->where()for. If I use ->query()though I have to write the whole query myself.
我知道我可以使用$this->db->query(),并编写我自己的 SQL 查询,但我还有其他需要使用的$this->db->where()要求。如果我使用->query()虽然我必须自己编写整个查询。
回答by Mark Unwin
$record = '123';
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get('accesslog');
then
然后
$query->num_rows();
should go a long way towards it.
应该有很长的路要走。
回答by useranon
try it out with the following code
用下面的代码试试
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();
}
回答by jonwayne
You can also run ->select('DISTINCT `field`', FALSE)and the second parameter tells CI not to escape the first argument. With the second parameter the output would be SELECT DISTINCT `field`instead of without the second parameter, SELECT `DISTINCT` `field`
您还可以运行->select('DISTINCT `field`', FALSE)并且第二个参数告诉 CI 不要转义第一个参数。使用第二个参数,输出将是SELECT DISTINCT `field`而不是没有第二个参数,SELECT `DISTINCT` `field`
回答by joash
Since the count is the intended final value, in your query pass
由于计数是预期的最终值,因此在您的查询传递中
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
计数返回值
回答by Sani Kamal
Simple but usefull way:
简单但有用的方法:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;

