如何在codeigniter中编写这个复杂的查询?

时间:2016-01-18 09:39:38

标签: php mysql codeigniter

我使用mysql并尝试将此查询写入Codeigniter模型。此查询在phpmyAdmin中完美运行。

SELECT 
        a.ar, 
        a.jabatan, 
        COUNT(*) AS JumlahWPBaru, 
        SUM( 
            CASE WHEN a.no_shim IS NOT NULL 
            THEN 1 
            WHEN a.no_shim IS NULL 
            THEN 0 
            END ) AS JumlahHimbauan
        FROM (

        SELECT 
            a.ar, 
            c.jabatan, 
            a.npwp, 
            a.kpp, 
            a.cab, 
            a.namawp, 
            b.kd_shim, 
            b.no_shim, 
            b.tgl_shim
        FROM mfwpbudi a
        LEFT JOIN tb_shimbauan b ON ( a.npwp = b.npwp ) 
        LEFT JOIN easystp_user c ON ( SUBSTR( a.ar, 1, 9 ) = c.id_user ) 
        WHERE a.tanggal_daftar >  '2013-12-31'
        AND c.jabatan =  '05E'
        ) AS a
        GROUP BY a.ar

这是我写的模型。

function m_data_penyampaian_shim()
{
    $this->db->query("SELECT 
        a.ar, 
        a.jabatan, 
        COUNT(*) AS JumlahWPBaru, 
        SUM( 
            CASE WHEN a.no_shim IS NOT NULL 
            THEN 1 
            WHEN a.no_shim IS NULL 
            THEN 0 
            END ) AS JumlahHimbauan
        FROM (

        SELECT 
            a.ar, 
            c.jabatan, 
            a.npwp, 
            a.kpp, 
            a.cab, 
            a.namawp, 
            b.kd_shim, 
            b.no_shim, 
            b.tgl_shim
        FROM mfwpbudi a
        LEFT JOIN tb_shimbauan b ON ( a.npwp = b.npwp ) 
        LEFT JOIN easystp_user c ON ( SUBSTR( a.ar, 1, 9 ) = c.id_user ) 
        WHERE a.tanggal_daftar >  '2013-12-31'
        AND c.jabatan =  '05E'
        ) AS a
        GROUP BY a.ar");
    $qry=$this->db->get();
    return $qry->result();
}

但是我收到了错误:

  

错误号码:1096

     

没有使用表格

     

SELECT *

     

文件名:C:\ xampp \ htdocs \ himbauanwpbaru \ system \ database \ DB_driver.php

     

行号:330

我如何解决这个问题?我在上面的代码中留下了什么吗? 我感谢任何建议和解决方案。 谢谢

1 个答案:

答案 0 :(得分:3)

$this->db->query()函数仅在成功或失败时返回TRUE / FALSE。它既不返回数据库结果集,也不设置查询计时器,或编译绑定数据,或存储查询以进行调试。它只是让您提交查询。大多数用户很少使用此功能。

尝试这种方式: -

$sql  = "SELECT 
        a.ar, 
        a.jabatan, 
        COUNT(*) AS JumlahWPBaru, 
        SUM( 
            CASE WHEN a.no_shim IS NOT NULL 
            THEN 1 
            WHEN a.no_shim IS NULL 
            THEN 0 
            END ) AS JumlahHimbauan
        FROM (

        SELECT 
            a.ar, 
            c.jabatan, 
            a.npwp, 
            a.kpp, 
            a.cab, 
            a.namawp, 
            b.kd_shim, 
            b.no_shim, 
            b.tgl_shim
        FROM mfwpbudi a
        LEFT JOIN tb_shimbauan b ON ( a.npwp = b.npwp ) 
        LEFT JOIN easystp_user c ON ( SUBSTR( a.ar, 1, 9 ) = c.id_user ) 
        WHERE a.tanggal_daftar >  '2013-12-31'
        AND c.jabatan =  '05E'
        ) AS a
        GROUP BY a.ar";

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