【问题标题】:Codeigniter Active record And Or combinations in where clause with multiple & nested groups带有多个和嵌套组的where子句中的Codeigniter活动记录和或组合
【发布时间】:2018-12-07 12:14:40
【问题描述】:

我有一个复杂的 SQL 查询,我想通过 Active Records 来实现它。此查询有几个与另一个条件组合在一起的 AND / OR 子句。我浏览了各种文章,他们说我们可以使用 group_start()group_end() 但我想知道一个组是否也可以在另一个组中启动?生成的序列号需要从外部查询生成的结果集中排除。实际上我在这里尝试使用 Join,但它没有用。任何关于加入这里的工作想法也将是可观的。

正如您在下面的查询中看到的,我使用双圆括号来表示组内的多个组。 生成的序列号也需要从外部查询的结果中排除。请告诉我它的 Codeigniter Active Record 等效代码是什么。

select * from table2 WHERE NOT table2.serial IN (select columnname from table where ((col < val and val < col) or (col < val and val < col) or(val=col and val=col)) AND incol=intval AND intcol=intval)

这里col是列名,val是DATE类型的值,intval是 一个整数值

【问题讨论】:

  • 是的!您可以在组内嵌套组,其方式与编写查询时在“纯”SQL 中用括号嵌套括号的方式相同

标签: codeigniter activerecord codeigniter-3 codeigniter-2


【解决方案1】:

试试这个语法

$this->db->select("*")->from("table");
    $this->db->group_start();
        $this->db->group_start();
            $this->db->where("val <",'col');
            $this->db->where("val <",'col');
        $this->db->group_end();
        $this->db->or_group_start();
            $this->db->or_where("val <",'col');
            $this->db->where("val <",'col');
        $this->db->group_end();
        $this->db->or_group_start();
            $this->db->or_where("val ",'col');
            $this->db->where("val ",'col');
        $this->db->group_end();
    $this->db->group_end();
    $this->db->where("incol ",'intval');
    $this->db->where("incol ",'intval');
    $this->db->get();
    $last_query = $this->db->last_query();

    $this->db->select('*')->from('table2');
    $this->db->where_not_in('serial',$last_query);
    $this->db->get();
    echo $this->db->last_query();

上面产生的查询字符串是

SELECT * FROM `table2` WHERE
     `serial` NOT IN(
    SELECT columnname FROM `table` WHERE
    (
        (`val` < 'col' AND `val` < 'col') OR
        (`val` < 'col' AND `val` < 'col') OR
        (`val` = 'col' AND `val` = 'col') 
    ) AND `incol` = 'intval' AND `incol` = 'intval'
);

【讨论】:

  • 为什么第一个参数使用双引号,第二个参数使用单引号?
  • @splash58,Single 或 double 在这种用法上没有区别。没有特殊含义。
  • 这不适用于 CI 2.x 中的活动记录类!在新的查询构建器类(自 CI 3.x 起)中引入了查询分组,它取代了活动记录类
  • @Harshwardhan 请检查问题中的一些更新,我错误地跳过了。请也提供该更新的代码行。
  • @Shobhit Gupta 检查更新的查询。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多