left join和inner join举例
1:创建两个表
/*
MySQL Data Transfer
Source Host: localhost
Source Database: test
Target Host: localhost
Target Database: test
Date: 2015/8/19 11:49:26
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_a
-- ----------------------------
CREATE TABLE `t_a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Table structure for t_b
-- ----------------------------
CREATE TABLE `t_b` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `t_a` VALUES ('1', 'a');
INSERT INTO `t_a` VALUES ('2', 'b');
INSERT INTO `t_a` VALUES ('3', 'c');
INSERT INTO `t_a` VALUES ('4', 'd');
INSERT INTO `t_b` VALUES ('1', 'a');
INSERT INTO `t_b` VALUES ('2', 'b');
INSERT INTO `t_b` VALUES ('5', 'a');
2:left join
select a.* from t_a a
left join t_b b
on a.name = b.name
运行结果:
select a.*,b.* from t_a a
left join t_b b
on a.name = b.name
运行结果:
3:inner join
select a.* from t_a a
inner join t_b b
on a.name = b.name
运行结果:
select a.*,b.* from t_a a
inner join t_b b
on a.name = b.name
注意:
left join和inner join,假设on和where条件不唯一的话,主表会查询出反复数据。
所以在实际应用中。请确保on条件的唯一性。
———————————————————————————————————————
我开通了微信订阅号“i小窝”。关注就可以第一时间看到我的原创文章以及我推荐的精彩文章: