2010-03-22 94 views
65

我使用CodeIgniter的Active Record类来查询MySQL数据库。我需要在一个字段设置为NULL表中选择行:用CodeIgniter查询MySQL,选择字段为NULL的行

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

这仅返回此查询:

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

archived字段是DATE场。

有没有更好的方法来解决这个问题?我知道我可以自己编写查询,但是我不想在整个代码中使用Active Record。

回答

116
where('archived IS NOT NULL', null, false) 
+13

请注意,当你这个第三个参数设置为FALSE,笨不会试图保护带反引号的字段或表名。 – 2012-01-19 15:55:27

+10

另外值得一提的是,当你传递一个数组参数时,你可以使用它:'where(array(“foo”=>“bar”,“archived IS NOT NULL”=> null))''。很不直观,但有效。 – Andrey 2013-11-28 17:05:31

5

空不能设置为字符串...

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

它正常工作时,空不裹入引号。

+1

这应该是正确的接受的答案 – GusDeCooL 2012-07-01 19:13:19

+3

@GusDeCooL不知道这实际上工作。 使用此输出...“字段不是”没有NULL。接受的答案似乎是正确做到这一点的方法。 http://ellislab.com/forums/viewthread/119444/#593454 - 给我更多的信息,我可以。 – andyface 2012-11-27 16:21:21

+7

-1,因为它不起作用! 我试过类似的变化: $ this-> db-> where('when_removed is',null); 给出了数据库错误,并显示生成的查询包括: ... WHERE“when_removed”是ORDER BY“last_name”asc ... – 2012-12-03 21:54:27

51

活动记录肯定有一些怪癖。当您将数组传递给$this->db->where()函数时,它将生成一个IS NULL。例如:

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

产生

WHERE `archived` IS NULL 

的夸克是不存在等效于负IS NOT NULL。有,然而,一个办法做到这一点产生正确的结果,仍然逃脱声明:

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

产生

WHERE `archived` IS NOT NULL 
+13

+1因为where('archived IS NOT NULL')'这仍然保护标识符和接受的答案不是。 – 2013-01-04 13:03:40

-2

一种方法来检查任何列为空与否是

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

在php中,如果列中有数据,则可以表示为True,否则为False 要在where命令中使用多个比较并检查列数据是否为空 做它像

这里是完整的例子,我是如何筛选where子句(Codeignitor)的列。最后一个节目非NULL压缩

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

我刚刚试过这个并输出它生成的SQL:'SELECT * FROM(\'test \')WHERE \'somebit \'='1'AND''status \'='Published'AND \'sc_id \'= 1'。检查列是否等于1并检查列是否非空是极为不同的。 – 2014-05-27 15:18:33

0

好得多使用以下 对于不为空

在哪里( '存档IS NOT NULL',NULL);

For null is null

where('archived',null);

0

只是为了给你另一种选择,你可以使用NOT ISNULL(archived)作为你的WHERE过滤器。

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

生成的查询是:

WHERE `column` IS NULL 
0

笨通过只留下不带参数的呼叫生成一个 “IS NULL” 查询:

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

生成的查询是:

WHERE archived IS NOT NULL; 

$这 - > DB->其中( '归档IS NOT NULL',); < <没必要

逆:

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

生成的查询是:

WHERE archived IS NULL; 
+0

OP正在寻找'IS NOT NULL'而不是'IS NULL' – AndFisher 2016-12-14 12:22:27

4

笨3

只有

+0

正在寻找这个..谢谢! – William 2018-02-15 09:23:34