比如说我有两张表,一张表是学生表,一张表是班级表,班级表对学生表是一对多的关系。建表语句如下:
create table class
(id int identity(1,1) primary key,
year int,
name varchar(50));
create table student
(id int identity(1,1) primary key,
classId int foreign key(classId) references class(id),
name varchar(50));
其中class是班级表,student是学生表
插入数据如下:
insert into class(year,name)
values(2017,'三年一班'),
(2017,'三年二班'),
(2017,'三年三班'),
(2017,'三年四班')
insert into student(classId,name)
values(1,'赵一'),
(2,'钱二'),
(2,'孙三'),
(3,'李四'),
(3,'周五'),
(3,'吴六'),
(3,'郑七'),
(2,'王九')
插入后的结果如图:
然后需要获得每个班级的人数,SQL语句如下:
select a.*,(select count(1) from student b where b.classId = a.id) as count from class a
查询结果为:
就获得了每个班的人数