[英]MySQL: How to return all rows in a table and count the amount of rows with matching ID from another table
[英]How to Count rows If Current Column `Id` is Matching from Another Table in Codeignitor PHP?
我正在 Codeignitor 中開發學校 erp。 我在計算行數時遇到了問題。 這里讓我解釋一下。
這是我的 Class 表。
這是我的觀點
所以,我想從表學生中計算學生,並在 class 名稱下方的框中打印數字。 如您所見,表 class 的id
與表 Student 中的 clumne class_id
匹配。
這是我的 Model 代碼:-
//get class list in box
function getClassList() {
$query = $this->db->select('*')->get('classes');
return $query->result_array();
}
我的 Controller:-
function classlist() {
if (!$this->rbac->hasPrivilege('student', 'can_view')) {
access_denied();
}
$this->session->set_userdata('top_menu', 'Student Information');
$this->session->set_userdata('sub_menu', 'student/search');
$data['title'] = 'Student Search';
$clist = $this->student_model->getClassList();
$data['clist'] = $clist;
$this->load->view('layout/header', $data);
$this->load->view('student/studentSearch', $data);
$this->load->view('layout/footer', $data);
}
}
在這里我的視圖頁面:-
<?php foreach ($clist as $key ) {
?>
<div class="info-box">
<a href="<?php echo base_url();?>student/stdlists/<?php echo $key['id']; ?>">
<span class="info-box-icon bg-green"><i class="fa fa-child"></i></span>
<div class="info-box-content">
<span class="info-box-text"><?php echo $key['class']; ?></span>
<span class="info-box-number">**I want to Print The Total Count here**</span>
</div>
</a>
</div>
<?php } ?>
</div>
您將需要在 function getClassList 中左加入和分組。
最終查詢應該是這樣的:
select count(t.id) as students_in_class, s.*
from class s
left join student t on s.id = t.class_id
group by t.class_id
但你使用 ORM 我不熟悉它....
希望這對你有用..
$this->db->where('id','class_id');
$this->db->get('student');
$number_of_rows=$this->db->num_rows();
print_r($number_of_rows);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.