mysql单独一个join是_MySQL中关于join的一个误区

我估计应该有一部分MySQL的小白用户跟我一样,以为 A left join B on a.key=b.key and condition 等价于 A left join B on a.key = b.key where condition

假设我们有两张表,分别存放某个对象的信息1+信息2、信息3+信息4,表结构如下:

CREATE TABLE `part1` (

`id` int(11) NOT NULL,

`info1` int(11) NOT NULL,

`info2` int(11) DEFAULT NULL,

PRIMARY KEY (`id`)

)

CREATE TABLE `part2` (

`id` int(11) NOT NULL,

`info3` int(11) NOT NULL,

`info4` int(11) DEFAULT NULL,

PRIMARY KEY (`id`)

)

然后我们往其中插入一些数据:

insert into part1(id,info1,info2)values(1,10,10),(2,20,20),(3,30,30);

insert into part2(id,info3,info4)values(1,10,null),(4,40,40),(2,20,20);

最终2张表的数据如下:

mysql> select * from part1;

+----+-------+-------+

| id | info1 | info2 |

+----+-------+-------+

| 1 | 10 | 10 |

| 2 | 20 | 20 |

| 3 | 30 | 30 |

+----+-------+-------+

select * from part2;

+----+-------+-------+

| id | info3 | info4 |

+----+-------+-------+

| 1 | 10 | NULL |

| 2 | 20 | 20 |

| 4 | 40 | 40 |

+----+-------+-------+

接下来我们看一个查询:

select * from part1 a left join part2 b on a.id = b.id and b.info4 = 20 order by a.id;

其结果如下:

+----+-------+-------+------+-------+-------+

| id | info1 | info2 | id | info3 | info4 |

+----+-------+-------+------+-------+-------+

| 1 | 10 | 10 | NULL | NULL | NULL |

| 2 | 20 | 20 | 2 | 20 | 20 |

| 3 | 30 | 30 | NULL | NULL | NULL |

+----+-------+-------+------+-------+-------+

呵呵,我明明写着b.info4=20嘛,为啥第一行和第三行冒出来了呢?

好吧,我错了,我改:

select * from part1 a left join part2 b on a.id = b.id where b.info4 = 20 order by a.id;

这下结果对了:

+----+-------+-------+------+-------+-------+

| id | info1 | info2 | id | info3 | info4 |

+----+-------+-------+------+-------+-------+

| 2 | 20 | 20 | 2 | 20 | 20 |

+----+-------+-------+------+-------+-------+

同样的一些类似的“奇怪”的SQL结果如下:

mysql> select * from part1 a left join part2 b on a.id = b.id and b.info4 is not null order by a.id;

+----+-------+-------+------+-------+-------+

| id | info1 | info2 | id | info3 | info4 |

+----+-------+-------+------+-------+-------+

| 1 | 10 | 10 | NULL | NULL | NULL |

| 2 | 20 | 20 | 2 | 20 | 20 |

| 3 | 30 | 30 | NULL | NULL | NULL |

+----+-------+-------+------+-------+-------+

(b.info4 is not null嘛,这结果明显很诡异)

知道是我理解错了,错在这里:

MySQL的连接查询中,ON后面的condition只是指定了从B表检索数据的方式,并不做任何的过滤,如果B表没有匹配的数据,则以NULL填充(注意,关键点在这里,并不做where过滤)。数据填充返回了以后,再执行where条件的过滤,如果没有where条件,就不做任何过滤了

注:以上测试使用的MySQL版本为:

mysql> select version();

+------------+

| version() |

+------------+

| 5.6.20-log |

+------------+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值