0

我被一个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。

提前致谢

4

2 回答 2

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);
于 2012-04-24T11:00:03.013 回答
1

This is the query:

$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";

You can directly use it like this:

$this->db->query($sql);
于 2012-04-24T10:45:15.410 回答