将sql查询转换为codeigniter

zqry0prt  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(310)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

两年前关门了。
改进这个问题
有人能帮我把这个sql查询转换成codeigniter吗

"SELECT *,
       (select nama_opd from c1db_pegawai.m_opd aopd where p.jabatan_lama_opd = aopd.id) lm_jabatan_lama_opd,
       (select nama_opd from c1db_pegawai.m_opd bopd where p.jabatan_baru_opd = bopd.id) br_jabatan_baru_opd,
       (select unit_kerja from c1db_pegawai.m_unit_kerja aunit where p.jabatan_lama_unit = aunit.id) lm_jabatan_lama_unit,
       (select unit_kerja from c1db_pegawai.m_unit_kerja bunit where p.jabatan_baru_unit = bunit.id) br_jabatan_baru_unit
       from sk_mutasi p;
wqsoz72f

wqsoz72f1#

使用查询生成器,您只需将这些选择分组即可。

$this->db->select('*')
    ->group_start()
        ->select('(SELECT nama_opd FROM c1db_pegawai.m_opd aopd WHERE p.jabatan_lama_opd = aopd.id) AS lm_jabatan_lama_opd')
    ->group_end()
    ->group_start()
        ->select('(SELECT nama_opd from c1db_pegawai.m_opd bopd WHERE p.jabatan_baru_opd = bopd.id) AS br_jabatan_baru_opd')
    ->group_end()
    ->group_start()
        ->select('(SELECT unit_kerja from c1db_pegawai.m_unit_kerja aunit where p.jabatan_lama_unit = aunit.id) AS lm_jabatan_lama_unit')
    ->group_end()
    ->group_start()
        ->select('(SELECT unit_kerja from c1db_pegawai.m_unit_kerja bunit where p.jabatan_baru_unit = bunit.id) AS br_jabatan_baru_unit')
    ->group_end()
    ->from('sk_mutasi p')
    ->get()
    ->result();

您甚至可以深入到另一个层次,只需使用查询生成器来创建这些子选择。
或者,您可以在查询语句中使用整个查询,如下所示:

$this->db->query('SELECT *,
       (select nama_opd from c1db_pegawai.m_opd aopd where p.jabatan_lama_opd = aopd.id) lm_jabatan_lama_opd,
       (select nama_opd from c1db_pegawai.m_opd bopd where p.jabatan_baru_opd = bopd.id) br_jabatan_baru_opd,
       (select unit_kerja from c1db_pegawai.m_unit_kerja aunit where p.jabatan_lama_unit = aunit.id) lm_jabatan_lama_unit,
       (select unit_kerja from c1db_pegawai.m_unit_kerja bunit where p.jabatan_baru_unit = bunit.id) br_jabatan_baru_unit
       from sk_mutasi p')
->result();

我想指出的是,这可能不是一个好的查询,您可能会得到更好的结果只是做一个连接,从这些额外的表中获取信息。

mzmfm0qo

mzmfm0qo2#

正如marcogmonteiro已经指出的-你真的必须在这里使用连接。
请尝试以下操作

$query = $this->db
    ->select('p.*, aopd.nama_opd AS lm_jabatan_lama_opd, bopd.nama_opd AS br_jabatan_baru_opd, aunit.unit_kerja AS lm_jabatan_lama_unit, bunit.unit_kerja AS br_jabatan_baru_unit')
    ->from('sk_mutasi p')
    ->join('c1db_pegawai.m_opd aopd', 'p.jabatan_lama_opd = aopd.id', 'left')
    ->join('c1db_pegawai.m_opd bopd', 'p.jabatan_baru_opd = bopd.id', 'left')
    ->join('c1db_pegawai.m_unit_kerja aunit', 'p.jabatan_lama_unit = aunit.id', 'left')
    ->join('c1db_pegawai.m_unit_kerja bunit', 'p.jabatan_baru_unit = bunit.id', 'left')
    ->get();

相关问题