MySql中多表联查是要注意的事项

本文介绍了MySQL中多表联查的基本概念,包括联合查询、内连接、外连接(左外连接和右外连接),并详细阐述了各种联查方式的效果和使用场景,通过实例展示了如何进行多表操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------

mysql建立多对多的结构关系

https://blog.youkuaiyun.com/m0_37602117/article/details/78819072

 

mysql建立自关联

https://blog.youkuaiyun.com/zhou120189162/article/details/83306132

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值