left join中条件放在on中与where中的区别

废话少说,先上demo。

用户表:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三');

客户表:

CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of customer
-- ----------------------------
INSERT INTO `customer` VALUES ('1', '张三', '111');
INSERT INTO `customer` VALUES ('2', '张三', '222');

来一条查询语句:

SELECT * from user LEFT JOIN customer on user.`name` = customer.username and customer.username = '456' 

结果:

1 张三 null null null

再来一条查询数据:

SELECT * from user LEFT JOIN customer on user.`name` = customer.username and customer.username = '456'  WHERE customer.username = '456'

结果:

null

当条件放在on中时,条件所关联的表会先过滤后关联,若是右表过滤后没有数据,进行关联时候,左表的数据依然正常显示。

当条件放在where中时,是对连接后的结果集进行过滤。这个时候影响的就是连接后的结果集了。所以,放在where中时候,返回为无数据。

不信?

执行下面这条sql试试:

SELECT * from user LEFT JOIN customer on user.`name` = customer.username    WHERE customer.username = '456'

谢谢。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值