首页 > 代码库 > MySQL多表连接查询
MySQL多表连接查询
MySQL多表连接查询
多表连接查询:
create table class(
cid int primary key auto_increment,
cname varchar(20)
)default charset=‘utf8‘;
create tablr stu(
sid int primary key auto_increment,
sname varchar(20).
cid int
);default charset=‘utf8‘;
insert into class(name) values(‘一班‘);
insert into class(name) values(‘二班‘);
insert into class(name) values(‘三班‘);
insert into class(name) values(‘四班‘);
insert into class(name) values(‘张三‘,1);
insert into class(name) values(‘李四‘,2);
insert into class(name) values(‘王五‘,2);
insert into class(name) values(‘杨六‘,3);
insert into class(name) values(‘赵七‘,5);
insert into class(name) values(‘周八‘,6);
select * from class;
select * from stu;
-------------------------------------
交叉连接:--没有任何条件,只需要将多张表的所有数据排列显示出来
select * from class,stu;
内连接:建立在两张或多张表之间,存在数据的关联关系
inner join
select * from 表A INNER JOIN 表B on 连接条件;
等价于
select * from 表A,表B where 表A.字段=表B.字段;
两张表:
select * from class INNER JOIN stu ON class.cid=stu.cid;
select * from class,stu, 表C WHERE class.cid=stu.cid AND 表A.字段=表C.字段;
三张表:
select * from student s,course c,score sc WHERE s.sid=sc.sid AND c.cid=sc.cid;
外连接:
左外连接 LEFT JOIN / LEFT OUTER JOIN
右外连接 RIGHT JOIN / RIGHT OUTER JOIN
外连接:左表或右表作为主表的情况下,主表的全部内容都会显示,而另一张表没有对应的数据则会补null
select * from class c LEFT JOIN stu s ON c.cid=s.cid;
select * from class c RIGHT JOIN stu s ON c.cid=s.cid;
MySQL多表连接查询