mysql中表与表之间的关系: 1:1 A表中的1条数据和B表中的1条数据有关联
一个妻子对应一个丈夫
1:N A表中的1条记录对应B表中的N条记录
一个经理对应N个员工 一个部门对应N个员工
N:N A表中的N条记录对应B表中的N条记录
N个老师对应N个学生
1:1 A表中的1条数据和B表中的1条数据有关联 一个妻子对应一个丈夫
drop table if exists wife;
create table wife(
id int comment 'id',name char(50) comment '姓名'
) comment '妻子表';
drop table if exists husband;
create table husband(
id int comment 'id',name char(50) comment '姓名'
) comment '丈夫表';
desc wife;
desc husband;
insert into wife values(1001,'Andy');
insert into husband values(1002,'Mike');
select * from wife w,husband h where w.id = h.id;
-- 看有老婆的就显示信息,没有老婆的就显示null
select * from husband h left join wife w on h.id = w.id;
1:N A表中的1条记录对应B表中的N条记录 一个经理对应N个员工 一个部门对应N个员工
-- 查看每个部门下面有多少员工?
-- 全连接:只有有关联的数据才会被查询出来,如果部门下面没有员工,这个部门也就不会显示了
select * from emp e,dept d where e.deptno = d.deptno;
select * from dept d left join emp e on d.deptno = e.deptno;
N:N A表中的N条记录对应B表中的N条记录(重要) N个老师对应N个学生 N个角色对应N个用户
drop table if exists teacher;
create table teacher(
t_id int,t_name char(50)
);
insert into teacher values
(1001,"张老师"),
(1002,"李老师"),
(1003,"王老师");
drop table if exists stu;
create table stu(
s_id int,s_name char(50)
);
insert into stu values
(1,"Andy"),
(2,"Mike"),
(3,"Bluce"),
(4,"Lee"),
(5,"Allen");
drop table if exists t_s_link;
create table t_s_link(
t_id int,s_id int
);
insert into t_s_link values
(1001,1),
(1001,1),
(1002,1),
(1002,3),
(1002,4);
-- 查询张老师教的学生有哪些
select t_name,s_name from teacher t,t_s_link ts,stu s where t.t_id = ts.t_id and ts.s_id = s.s_id
and t.t_name = '张老师';
-- 用join的方式写
select t_name,s_name from teacher t join t_s_link ts join stu s on t.t_id = ts.t_id and ts.s_id = s.s_id
and t.t_name = '张老师'; -- 正确
select t_name,s_name from teacher t join t_s_link ts on t.t_id = ts.t_id join stu s on ts.s_id = s.s_id
and t.t_name = '张老师'; -- 正确
-- 符合逻辑 查询所有老师教的学生有谁
select t_name,group_concat(s_name) from teacher t,t_s_link ts,stu s where t.t_id = ts.t_id and ts.s_id = s.s_id
group by t_name;