【问题标题】:Nested where clauses codeigniter mysql query嵌套where子句codeigniter mysql查询
【发布时间】:2012-08-13 15:52:07
【问题描述】:

有没有办法嵌套 where 子句?例如:

SELECT * FROM table WHERE (colA = 'valueA' AND colB = 'valueB') OR (colA = 'valueC' AND colB = 'valueD')

我知道我可以将其写入 query 函数调用,例如:

$this->db->query("SELECT ...")

但我想知道在 codeigniter 中是否有“正确”的方法来做到这一点,例如:

$this->db->where(array('colA'=>'valueA'), array('colB'=>valueB'))->or_where(array('colA'=>'valueC'), array('colB'=>'valueD'))

谢谢

【问题讨论】:

    标签: codeigniter


    【解决方案1】:

    现在有了 codeigniter 3,请查看更新!
    没有数组的 where() 方法使用变体可以让你这样做。在这些情况下,我通常只是将部件构建成一个长字符串,如下所示:

    $this->db->where("
        (
        (colA = '".$this->db->escape($v0)."' and colB = '".$this->db->escape($v1)."') 
        or 
        (colA = '".$this->db->escape($v2)."' and colB = '".$this->db->escape($v3)."') 
        )
    ");
    

    可以使用escape(进行一些自动检测)或escape_strescape_like_str 手动完成转义,具体取决于预期的参数或使用的谓词。

    如果我在使用Datamapper library 的项目中,我更喜欢在构建此类查询时使用group_start()group_end() 方法,它们有一个lot of different flavor

    更新

    现在有了 Codeigniter 3,其中 have grouping methods 在查询构建器中,所以您可以执行 ->group_start()s 和 ->group_end()s。

    【讨论】:

    • 啊,谢谢! :) 这比$this->db->query("...") 版本好一点。谢谢。
    【解决方案2】:

    你也可以试试

    $this->db->where(condition1);
    $this->db->or_where(condition2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多