Mysql查询:已注册的候选人数和可用的席位数

时间:2012-04-24 10:17:22

标签: php mysql codeigniter

我遇到了一个mysql查询。我有三张桌子:

表名:老师

teacherid  teachername 
 1001           ABC
 1002           XYZ

表名:批次

batchid   batchname  batch_type     class   batchinstructor     seat
   1        Solar        1            Five     1001               40
   2        Earth        2            Six      1002               40

表名:学生

    studentid studentname batchid
     1          Bon Jovi     1
     2          Shane Warne  2
     3          John Denver  1
     4          Steve Wuagh  2
     5          Perterson    2

我想要实现的目标

 batchname class  teachername seat  students_enrolled  seat_available
   Solar   Five    ABC          40           2              38
   Earth   six     XYZ          40           3              37

我正在使用codeigniter并设法实现上面提到的所有内容students_enrolledseat_available

这是我尝试过的代码。

      function batch_list($perPage,$uri) { 
    $this->db->select('*');
    $this->db->from('batch');
    $this->db->join('teacher', 'batch.batchinstructor = teacher.teacherid');
    $this->db->order_by('batchid','DESC');
    $getData = $this->db->get('', $perPage, $uri);
    if($getData->num_rows() > 0)
    return $getData->result_array();
        else
        return null;
    }

请您帮我解决mysql查询问题。请注意我使用的是Codeigniter。

提前致谢

2 个答案:

答案 0 :(得分:2)

在纯SQL中,您想要的查询是:

SELECT
  b.batchname, b.class, t.teachername, b.seat,
  COUNT(s.studentid) AS students_enrolled,
  b.seat - COUNT(s.studentid) AS seat_available
FROM batch b
LEFT JOIN Teacher t ON t.teacherid = b.batchinstructor
LEFT JOIN students s ON s.batchid = b.batchid
GROUP BY s.batchid
ORDER BY b.batchid DESC

您需要做的就是翻译这个CodeIgniter - 正如@Broncha建议的那样,您可以这样做:

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

答案 1 :(得分:1)

这是查询:

$sql = "select 
b.batchname,
b.class,
t.teachername,
b.seat,
count(s.id) as students_enrolled,
(seat - count(s.id)) as seat_available,
from batch b
join teacher t on t.teacherid = b.batchinstructor
join student s on s.batchid = b.batchid
group by s.batchid
order by b.batchid desc";

您可以直接使用它:

$this->db->query($sql);