gpt4 book ai didi

php - Mysql查询: Number of candidates enrolled and seat available

转载 作者:行者123 更新时间:2023-11-29 06:08:32 24 4
gpt4 key购买 nike

我被 mysql 查询困住了。我有三张 table :

表名称:教师

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。

提前致谢

最佳答案

在纯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);

关于php - Mysql查询: Number of candidates enrolled and seat available,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10295964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com