mysql中left join right join inner join用法分析

 mysql数据库中的关联查询,基本都会用到left join,right join,inner join等查询方式,今天来说说这三种用法的区别

1.创建表test1,test2,插入测试数据

#创建表sql语句#
CREATE TABLE test1(
    id int(10) AUTO_INCREMENT PRIMARY KEY, 
    name char(20) 
 ) 
CREATE TABLE test2(
    bid int(10) AUTO_INCREMENT PRIMARY KEY, 
    mobile char(20) 
 ) 
#插入测试数据sql语句#
INSERT INTO test1 VALUES ( 1, '小明' ) , ( 2, '小强' ) , ( 3, '小王' ) , ( 4, '小张' ) , ( 5, '小东' );
INSERT INTO test2 VALUES ( 1, '13625878968' ) , ( 2, '13582687245' ) , ( 3, '13802598746' ) , ( 4, '15025893698' ) , ( 8, '13582584789' );

2.测试left join,right join,inner join用法 

#left join(左连接)#
select a.*,b.* from test1 as a left join test2 as b on a.id=b.bid
结果如图
  
影响行数为5行,左表(test1)的记录将会全部表示出来,而右表(test2)只会显示符合搜索条件的记录(例子中为: test1.id = test2.bid). 
test2表记录不足的地方均为NULL
#right join(右连接)#
select a.*,b.* from test1 as a right join test2 as b on a.id=b.bid
结果如图
  
影响行数为5行,与left join的结果刚好相反,这次是以右表(test2)为基础的,test1表不足的地方用NULL填充
#inner join(内连接)#
select a.*,b.* from test1 as a inner join test2 as b on a.id=b.bid
结果如图
  
影响行数为4行,这里只显示出了 test1.id = test2.bid的记录.这说明inner join并不以谁为基础,它只显示符合条件的记录,精确匹配
原文地址:https://www.cnblogs.com/yqzc/p/6762477.html