SQL多对多

现有学生表teacher(图1),学生表student(图2),已知张老师的学生有小明小红小敏,王老师的学生有小明小峰,李老师暂时没有学生
a.建立老师和学生的对应关系
b.书写SQL,查出所有老师的id和此老师对应的学生数量

数据准备

CREATE table teacher(
    id INT UNIQUE,
    name VARCHAR(32)
)
INSERT INTO teacher (id,name)  SELECT 1,"张老师" UNION ALL SELECT 2,"王老师" UNION ALL SELECT 3,"李老师" ;```

![图1-老师表](http://upload-images.jianshu.io/upload_images/2240277-a53a4209c327de26.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

CREATE TABLE student(
id INT ,
name VARCHAR(32)
)```

INSERT INTO student (id,name) SELECT 1,"小明" UNION ALL SELECT 2,"小红" UNION ALL SELECT 3,"小峰" UNION ALL SELECT 4,"小敏"```

![图2-学生表](http://upload-images.jianshu.io/upload_images/2240277-c42f3455e0a118cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

CREATE TABLE stu_teacher(
id int UNIQUE,
t_name VARCHAR(32),
s_name VARCHAR(32)
)```

INSERT into stu_teacher (id,t_name,s_name) SELECT 1,"张老师","小明" UNION ALL SELECT 2,"张老师","小红" UNION ALL SELECT 3,"张老师","小敏" 
UNION ALL SELECT 4,"王老师","小明" UNION ALL SELECT 5,"王老师","小峰" UNION ALL SELECT 6,"李老师",null ```
**注意:李老师的学生要设置成null!**
![图3-中间表](http://upload-images.jianshu.io/upload_images/2240277-bd3c065e8789d639.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

Q:查出所有老师的id和此老师对应的学生数量
```select t.id '教师ID',count(s.s_name) as '学生数' from teacher t LEFT JOIN stu_teacher s on t.name=s.t_name group by t.id;```

![结果](http://upload-images.jianshu.io/upload_images/2240277-eb1a5c6554528cfa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

你可能感兴趣的:(SQL多对多)