CodeIgniter:如何执行Select(不同的Fieldname) MySQL查询

时间:2022-07-15 04:28:20

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->查询(),并编写我自己的SQL查询,但是我还有其他需要使用$this->db->()的需求。如果我使用->查询(),尽管我必须自己编写整个查询。

3 个解决方案

#1


85  

$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.

应该有很长的路要走。

#2


9  

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();  
}

#3


7  

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不要转义第一个参数。对于第二个参数,输出将选择不同的' field '而不是没有第二个参数,选择' DISTINCT ' field '

#1


85  

$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.

应该有很长的路要走。

#2


9  

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();  
}

#3


7  

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不要转义第一个参数。对于第二个参数,输出将选择不同的' field '而不是没有第二个参数,选择' DISTINCT ' field '