需要查询帮助

时间:2015-04-12 14:31:51

标签: database codeigniter

我当前的查询是:



public function teachers_manage() {

     
      $this->db->select('users.user_id, teacher_id, COUNT(student_id) AS S, COUNT(DISTINCT(users.class)) AS C, schools.region, schools.school_name');      
      $this->db->from('teacher_student_conn');      
      $this->db->join('users', 'teacher_student_conn.student_id=users.user_id','left');
     
      $this->db->join('schools', 'schools.school_id=users.school_id');
      $this->db->where('users.deactivated_at = "0000-00-00 00:00:00" OR users.deactivated_at IS NULL ');
      
      $this->db->where('users.role_id', '1');
      $this->db->group_by("teacher_student_conn.teacher_id");
      $result=$this->db->get();
        return $result->result();
        
  }




它向我展示了教师和每位教师他教授的课程数量以及他教授的学生人数。我已经通过users加入了2个表格 - teacher_student_connusers=user_id=teacher_student_conn.student_id,并且我已经将不允许停用学生的条款放在哪里 - 显示了活跃的学生。但如何做到这一点也教老师?另一个联接将改变结果。我只想为教师添加where子句以使其活跃。 我的表看起来像这样:

users

  • USER_ID
  • 学校ID
  • ROLE_ID
  • created_at
  • deactivated_at

    教师student_conn

  • ID

  • teacher_id
  • student_id数据
  • created_at

1 个答案:

答案 0 :(得分:1)

我建议为" status"添加一列更容易区分学生和教师的状态。 这是我推荐的查询

SQL查询:

  select 
    from users a
    join teacher-student_conn b on a.user_id = b.student_id
    join schools c on c.school_id = a.school_id
    where (a.status = "Deactivated") and (b.status = "Deactivated")

对于codeigniter:

  $this->db->select('a.user_id, b.teacher_id, COUNT(b.student_id) AS S, COUNT(DISTINCT(a.class)) AS C, c.region, c.school_name');
  $this->db->join('teacher_student_conn b', 'b.student_id = a.user_id','left');

  $this->db->join('schools c', 'c.school_id = a.school_id');
  $this->db->where('a.status = "Deactivated" or b.status = "Deactivated" ');

  $this->db->where('a.role_id', '1');
  $this->db->group_by("b.teacher_id");
  $result=$this->db->get("users a");
  return $result->result();