table-a:
CREATE TABLE `table_a` (
`id` bigint(12) NOT NULL,
`name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(6) DEFAULT NULL,
`gender` tinyint(2) DEFAULT NULL,
`company` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
table-b:
CREATE TABLE `table_b` (
`id` bigint(12) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(6) DEFAULT NULL,
`gender` tinyint(2) DEFAULT NULL,
`company` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
table-a:
INSERT INTO `table_a` (`id`, `name`, `age`, `gender`, `company`) VALUES('1','aa','21','1','公司1');
INSERT INTO `table_a` (`id`, `name`, `age`, `gender`, `company`) VALUES('2','bb','22','0','公司2');
INSERT INTO `table_a` (`id`, `name`, `age`, `gender`, `company`) VALUES('3','cc','23','1','公司3');
table-b:
INSERT INTO `table_b` (`id`, `name`, `age`, `gender`, `company`) VALUES('1','bb','22','0','公司2');
INSERT INTO `table_b` (`id`, `name`, `age`, `gender`, `company`) VALUES('2','cc','23','1','公司3');
INSERT INTO `table_b` (`id`, `name`, `age`, `gender`, `company`) VALUES('3','ff','26','1','公司C');
两张表数据如下图:
Left join:两表共有+左表独有,SQL如下:
SELECT * FROM table_a a LEFT JOIN table_b b ON a.name = b.name
查询结果如下:
Right join:两表共有+右表独有,SQL如下:
SELECT * FROM table_a a RIGHT JOIN table_b b ON a.name = b.name
查询结果如下:
Inner join:两表共有,SQL如下:
SELECT * FROM table_a a INNER JOIN table_b b ON a.name = b.name
查询结果如下:
SELECT a.* FROM table_a a LEFT JOIN table_b b ON a.name = b.name WHERE b.name IS NULL
查询结果:
SELECT b.* FROM table_a a RIGHT JOIN table_b b ON a.name = b.name WHERE a.name IS NULL
查询结果:
SELECT a.name,a.age,a.gender,a.company FROM table_a a
UNION
SELECT b.name,b.age,b.gender,b.company FROM table_b b
查询结果:
此处如果使用union all的得到的结果是不同的,SQL如下:
SELECT a.name,a.age,a.gender,a.company FROM table_a a
UNION ALL
SELECT b.name,b.age,b.gender,b.company FROM table_b b
对比union和union all的查询结果可知:
union会合并相同的查询结果,union all不会!
SELECT a.name,a.age,a.gender,a.company FROM table_a a LEFT JOIN table_b b ON a.name = b.name WHERE b.name IS NULL
UNION
SELECT b.name,b.age,b.gender,b.company FROM table_b b LEFT JOIN table_a a ON a.name = b.name WHERE a.name IS NULL
查询结果如下: