如何在codeigniter中构建嵌套查询?

时间:2017-01-07 11:09:19

标签: php mysql codeigniter database-performance

下面是查询来获取不同表中不同数据的计数。

select(
        select count(*)
        from teachers
        where teacher_status = 1
  )as teacher_count,
  (
        select count(*)
        from students
        where student_status = 1
  )as students_count,
  (
        select count(*)
        from housekeepers
        where housekeeper_status = 1
  )as housekeeping_count,
  ( 
        select count(*)
        from students
        where student_status = 1 and
              gender = "Male"
  ) as total_male_student_count,
  ( 
        select count(*)
        from students
        where student_status = 1 and
              gender = "Female"
  ) as total_female_student_count

现在我想在codeigniter构建器类的帮助下在codeigniter中构建这个单一查询,所以有人可以指导我...

运行单个查询的目的是最小化数据库命中。

提前致谢.. !!!

1 个答案:

答案 0 :(得分:3)

您可以使用:get_compiled_select 像这样

$this->db->select('count(*) as count');
$this->db->from('teacher_status');
$teacher_status = $this->db->get_compiled_select();

$this->db->select("select($teacher_status)as teacher_count, ... ");
this->db ...

并用于其他人。