日期:2014-05-17  浏览次数:21408 次

求助:如何查询教师表,同时显示 教师姓名+教师的学生的个数
教师表

1 张三
2 李四

学生表 
ID 姓名 老师ID
1 学生A 1
2 B 1
3 C 2

查询结果
ID 姓名 学生个数
1 张三 2
2 李四 1

感谢!膜拜

------解决方案--------------------
教师表 --teacher(teacherID,teacherName)
学生表 --student(StudentID,StudentName,teacherID)
SQL code

select tea.teacherName,Count(stu.StudentID) as StudentNum 
from student stu

left join teacher tea
on tea.teacherID=stu.teacherID

group by teacherName

------解决方案--------------------
SQL code

create table tea(t_id number(10),t_name varchar2(20));
insert into tea values(1,'张三');
insert into tea values(2,'李四');

create table stu(s_id number(10),s_name varchar2(20),t_id number(10));
insert into stu values (1,'学生A',1);
insert into stu values (2,'学生B',2);
insert into stu values (3,'学生C',1);
insert into stu values (4,'学生D',1);
insert into stu values (5,'学生E',2);


select a.t_id,a.t_name 姓名,count(b.s_id) 学生个数
from tea a,stu b
where a.t_id=b.t_id
group by a.t_id,a.t_name
order by a.t_id

t_id  姓名   学生个数
----------------------
1      张三     3
2      李四     2