这个codeigniter查询如何执行?

时间:2015-01-14 07:42:57

标签: php mysql codeigniter codeigniter-2

这是(1):

SELECT `message`, `from` FROM (`chat_messages`) WHERE `from` = '1' AND `delivered` = 1 OR `to` = '1' AND `delivered` = 1

与此(2)相同

SELECT `message`, `from` FROM (`chat_messages`) WHERE (`from` = '1' AND `delivered` = 1) OR (`to` = '1' AND `delivered` = 1) 

用于生成结果(1)的codeigniter方法链式查询是

$this->db->select('message,from')->from('chat_messages')->where(array('from' => $user, 'delivered' => 1))->or_where('to', $user)->where('delivered', 1);

并且生产(2)我使用了这个

$where = "(`from` = '1' AND `delivered` = 1) OR (`to` = '1' AND `delivered` = 1)";
$this->db->select('message,from')->from('chat_messages')->where($where);

有人可以解释一下编写CI查询的最佳方法(从上面开始)吗? AND在第一个例子中是否优先考虑?

2 个答案:

答案 0 :(得分:1)

$this->db->select('message,from')->from('chat_messages')->where(array('from' => $user, 'delivered' => 1))->or_where('to', $user)->where('delivered', 1);

此代码使查询类似

from = 'somthing' and delivered='something' or to='something' and delivered='something'

因此根据您的预期结果会产生错误的结果。第四个是正确的。你可以使用它。

答案 1 :(得分:0)

这是最好的方法

$where = "(`from` = '1' AND `delivered` = 1) OR (`to` = '1' AND `delivered` = 1)";
$this->db->select('message,from')->from('chat_messages')->where($where);

请记住1件事,简而言之就是乘法,或者是加法,因此根据bodmas规则并优先考虑。这是我们在编码中遵循的某种实际例子。所以总是将AND,OR粘合在一起,如下所示:

(`from` = '1' AND `delivered` = 1) OR (`to` = '1' AND `delivered` = 1)