如何在其中强制将'or wheres'连接到sql的情况下进行选择?

时间:2018-11-07 17:46:01

标签: sql codeigniter

我需要进行选择:

select * from posts where active = 1 //mandatory where url <> 'thisurl' //mandatory or where id1 = 1 or where id2 = 2

明白了吗? 另外,我正在使用Codeigniter active record,所以如果有人可以帮助您 在翻译时,我会很感激。

5 个答案:

答案 0 :(得分:1)

尝试如下

 select * from posts where active = 1       //mandatory
                     and url <> 'thisurl' //mandatory
                     and ( id1 =1 or id2 =2)

答案 1 :(得分:1)

在Codeigniter查询构建器术语中:

$this->db->select('*');
$this->db->where('active', 1);
$this->db->where('url !=', 'thisurl');
$this->db->group_start();
     $this->db->or_where('id1', 1);
     $this->db->or_where('id2', 2);
$this->db->group_end();

$query = $this->db->get();
return $query->result();

上面的代码将始终强制使用active = 1和url <>'thisurl',并至少强制执行id1 = 1或id2 = 2

答案 2 :(得分:0)

你可以做到

SELECT* 
FROM posts 
WHERE active = 1       //
AND url <> 'thisurl' //mandatory
OR id1 = 1 
OR id2 = 2

答案 3 :(得分:0)

别忘了括号!

SELECT * from posts 
WHERE (active = 1 AND url <> 'thisurl') OR id1 = 1 OR id2 = 2

答案 4 :(得分:0)

您可以使用$ where简化在哪里查询

$this->db->select('*');
$this->db->from('posts');
$where ="(
        active = 1       //mandatory
        where url <> 'thisurl' //mandatory
        or where id1 = 1 
        or where id2 = 2
        )";
$this->db->where($where);
$result = $this->db->get();