【问题标题】:How to make a case condition inside codeigniter query如何在codeigniter查询中创建case条件
【发布时间】:2020-02-25 04:44:45
【问题描述】:

我有一些这样的查询:

$this->db->query("SELECT `no_request`,`date_in`,`location`,`d_point`,`username`,SUM(request.`persen`) AS 'Persen',
        CASE 
            WHEN SUM(Persen) = 0 THEN 'Pending'
            WHEN SUM(persen) = 100 THEN 'Complete'
            WHEN SUM(persen) > 0 AND SUM(persen) < 100 THEN 'On Process'
        END AS 'states'
        FROM request WHERE `location` = '$lokasi' GROUP BY `no_request`
        HAVING 
        CASE 
            WHEN `Persen` = 0 THEN `states` = 'Pending'
        END", TRUE)->result_array();

我想从 codeigniter 生成原始查询,但我的查询有一些问题:

$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen);
$this->db->select("
CASE
  WHEN SUM('persen') = 0 THEN 'Pending'
  WHEN SUM('persen') = 100 THEN 'Complete'
  WHEN SUM('persen') > 0 SUM('persen') < 100 THEN 'On Process'
END", FALSE);
$this->db->from($this->table);
$this->db->where($this->location . ' = ' . $location);
$this->db->group_by($this->group);

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

我的查询有误吗?或者我不能在$this-&gt;db-&gt;select() 中使用case

【问题讨论】:

    标签: sql codeigniter


    【解决方案1】:

    $this-&gt;db-&gt;select() 确认一个任意的第二个参数。如果您将其设置为 FALSECodeIgniter 将不会尝试确保您的字段或表名称。如果您需要复合选择说明,其中编程的离开字段可能会破坏它们,这很有帮助。

    供参考:-https://codeigniter.com/userguide3/database/query_builder.html#selecting-data

    【讨论】:

    • 所以我必须删除该查询中的 FALSE 吗?或者一些代码让我的查询工作?
    【解决方案2】:

    我的查询出现了一些错误,使我的查询无法正常工作,但现在代码很好,我已经完成了我的代码,我像这样更改我的查询:

    从此代码:

    $this->db->select($this->fetching_column);
    $this->db->select_sum($this->persen);
    $this->db->select("
    CASE
      WHEN SUM('persen') = 0 THEN 'Pending'
      WHEN SUM('persen') = 100 THEN 'Complete'
      WHEN SUM('persen') > 0 SUM('persen') < 100 THEN 'On Process'
    END", FALSE);
    $this->db->from($this->table);
    $this->db->where($this->location . ' = ' . $location);
    $this->db->group_by($this->group);
    $result = $this->db->get();
    

    变成了这样:

    $this->db->select($this->fetching_column);
    $this->db->select_sum($this->persen, 'Persen');
    $this->db->select("
      CASE 
        WHEN SUM(Persen) = 0 THEN 'Pending'
        WHEN SUM(Persen) = 100 THEN 'Complete'
        WHEN SUM(Persen) > 0 AND SUM(Persen) < 100 THEN 'On Process'
      END AS 'states'");
    $this->db->from($this->table);
    $this->db->where($this->location, $location);
    $this->db->group_by($this->group);
    $result = $this->db->get();
    

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 1970-01-01
      • 2015-10-07
      • 2015-05-19
      • 1970-01-01
      • 2021-08-04
      • 2021-08-27
      • 1970-01-01
      • 2018-02-24
      相关资源
      最近更新 更多