Querying MySQL with CodeIgniter, selecting rows where field is NULL

北战南征 提交于 2019-12-17 15:39:28

问题


I'm using CodeIgniter's Active Record class to query the MySQL database. I need to select the rows in a table where a field is not set to NULL:

$this->db->where('archived !=', 'NULL');
$q = $this->db->get('projects');

That only returns this query:

SELECT * FROM projects WHERE archived != 'NULL';

The archived field is a DATE field.

Is there a better way to solve this? I know I can just write the query myself, but I wan't to stick with the Active Record throughout my code.


回答1:


where('archived IS NOT NULL', null, false)



回答2:


The Active Record definitely has some quirks. When you pass an array to the $this->db->where() function it will generate an IS NULL. For example:

$this->db->where(array('archived' => NULL));

produces

WHERE `archived` IS NULL 

The quirk is that there is no equivalent for the negative IS NOT NULL. There is, however, a way to do it that produces the correct result and still escapes the statement:

$this->db->where('archived IS NOT NULL');

produces

WHERE `archived` IS NOT NULL



回答3:


Null must not be set to string...

$this->db->where('archived IS NOT', null);

It works properly when null is not wrapped into quotes.




回答4:


CodeIgniter 3

Only:

$this->db->where('archived IS NOT NULL');

The generated query is:

WHERE archived IS NOT NULL;

$this->db->where('archived IS NOT NULL',null,false); << Not necessary

Inverse:

$this->db->where('archived');

The generated query is:

WHERE archived IS NULL;



回答5:


Much better to use following For is not null

where('archived IS NOT NULL', null);

For is null

where('archived', null);




回答6:


And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.




回答7:


Codeigniter generates an "IS NULL" query by just leaving the call with no parameters:

$this->db->where('column');

The generated query is:

WHERE `column` IS NULL



回答8:


$this->db->or_where('end_date IS', 'NULL', false);




回答9:


You can do (if you want to test NULL)

$this->db->where_exec('archived IS NULL) 

If you want to test NOT NULL

$this->db->where_exec('archived IS NOT NULL) 



回答10:


One way to check either column is null or not is

$this->db->where('archived => TRUE);
$q = $this->db->get('projects');

in php if column has data, it can be represent as True otherwise False To use multiple comparison in where command and to check if column data is not null do it like

here is the complete example how I am filter columns in where clause (Codeignitor). The last one show Not NULL Compression

$where = array('somebit' => '1', 'status' => 'Published', 'archived ' => TRUE );
$this->db->where($where);


来源:https://stackoverflow.com/questions/2489453/querying-mysql-with-codeigniter-selecting-rows-where-field-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!