2017-02-20 102 views
1

这里是部门表如何显示每个部门的教员总数? SQL查询

department_id | department_name 
1    computers 
2    maths 
3    physics 
4    mba 

这里是教官表

instructor_id | department_id | name 
1    1    abc 
2    2    manu 
3    2    raju 
4    3    jaya 
5    4    man 

从上面的代码如何显示教师的总数为各个部门?

查询会是什么? 请帮忙。

我在codeigniter中做它。

+0

我尝试'内部加入'与'组'通过',但我收到错误为'列'部门标识'字段列表中含糊不清' – Kirataka

+0

我相信你想要这样的东西http://stackoverflow.com/questions/35340801/MySQL的选从 - 类别 - 在表-Y-其中-计数的最的categorys产物往复 –

回答

1
select d.department_id, count(*) as num_instructors 
from departments d 
    inner join instructors i on i.department_id = d.department_id 
group by d.department_id; 
1
SELECT COUNT(i.instructor_id) as `instructor_count`, d.department_name 
FROM instructor AS i 
JOIN department ON d.department_id = i.department_id 
GROUP BY i.department_id" 
1

您可以尝试使用下面我的解决方案概念化,看看它是否能帮助,

为了避免并发症,你可以随便去直接

<?php 
//connection 
$link = mysqli_connect("localhost","root","","database_name") or die("Couldn't make connection."); 

$computer_department_id = //the value 
$query = mysqli_query($link, "SELECT department_id FROM instructure_table WHERE department_id='$computer_department_id')"); 
$total = mysqli_num_rows($query); 

echo $total; //this one will display the total number of instructors in computer department 
?> 

如果你喜欢

<?php 
//connection 
$link = mysqli_connect("localhost","root","","database_name") or die("Couldn't make connection."); 

$computer_department = //the value 
$query = mysqli_query($link, "SELECT department_id 
FROM instructure_table AS t 
WHERE EXISTS (SELECT department_id 
       FROM department_table AS d 
       WHERE d.department_id = t.department_id AND department_id='$computer_department')"); 
$total = mysqli_num_rows($query); 

echo $total; //this one will display the total number of instructors in computer department 
?> 

因此,如果您将查询放置在部门行中,即使对部门的查询位于重复区域中,它仍然适用于您。问候

相关问题