1.简单介绍一下多表联查的概念
当要查询的数据在多张表时,使用多表联查
2.多表联查的分类
MySQL联合查询
交叉联合查询 cross join
内连接联合查询 inner join (MySQL简写join)
外连接联合查询: 左外连接联合查询 left outer join (MySQL简写left join)
右外连接联合查询 right outer join (MySQL简写right join)
3.创建两张表
create table table1(
customer_id varchar(20) not null,
city varchar(20) not null,
primary key(customer_id)
) default charset = utf8
#----------------------------------------------------------------
create table table2(
order_id int not null auto_increment,
customer_id varchar(20),
primary key(order_id)
)default charset = utf8
#-----------------------------------------------------------------------
insert into table1(customer_id,city) values
('tedu','hangzhou'),('jd','shanghai'),('tx','hangzhou'),('baidu','hangzhou')
insert into table2(customer_id) values
('tedu'),('tedu'),('jd'),('jd'),('jd'),('tx'),(Null)
4.具体的介绍
1 cross join 效果
select * from table1 cross join table2
得到一张很大的数据表(28条数据记录 4*7)
这样的数据表称为两张数据表的笛卡尔积
2 inner join 效果【分为有条件的内连接和无条件的内连接】
select * from table1 inner join table2
其效果与cross join是一样的
得到一张很大的数据表(28条数据记录 4*7)
这样的数据表称为两张数据表的笛卡尔积
3 left outer join效果
不能直接让两张表进行左外连接
select * from table1 left join table2
左外连接是在内连接基础上进行的
首先让两张表先做“有条件”的内连接。
条件就是两张表要有共同列,在共同列上做内连接
然后才能进行左外连接。
有条件的内连接
select * from table1 join table2 on
table1.customer_id = table2.customer_id
在有条件的内连接的基础上做左外链接
select * from table1 left join table2 on
table1.customer_id = table2.customer_id
4 right outer join效果
不能直接让两张表进行右外连接
select * from table1 right join table2
右外连接是在内连接基础上进行的
首先让两张表先做“有条件”的内连接。
条件就是两张表要有共同列,在共同列上做内连接
然后才能进行右外连接。
select * from table1 join table2 on
table1.customer_id = table2.customer_id
select * from table1 right join table2 on
table1.customer_id = table2.customer_id