废话少说,先上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'
谢谢。