如下先创建2个表,aa bb.
CREATE table aa(
uid int(20) not null,
name VARCHAR(30) not null
)engine=innodb default charset=utf8mb4 COLLATE utf8mb4_general_ci;
INSERT INTO `aa`(`uid`, `name`) VALUES (10, '张芳');
INSERT INTO `aa`(`uid`, `name`) VALUES (11, '王凯');
INSERT INTO `aa`(`uid`, `name`) VALUES (12, '张学友');
INSERT INTO `aa`(`uid`, `name`) VALUES (13, '陈真');
INSERT INTO `aa`(`uid`, `name`) VALUES (14, '向佳');
INSERT INTO `aa`(`uid`, `name`) VALUES (15, '徐州');
CREATE table bb(
uid int(20) not null,
name VARCHAR(30) not null
)engine=innodb default charset=utf8mb4 COLLATE utf8mb4_general_ci;
INSERT INTO `bb`(`uid`, `name`) VALUES (110, '王海川');
INSERT INTO `bb`(`uid`, `name`) VALUES (111, '任海波');
INSERT INTO `bb`(`uid`, `name`) VALUES (121, '陈海杰');
INSERT INTO `bb`(`uid`, `name`) VALUES (131, '陈勇');
INSERT INTO `bb`(`uid`, `name`) VALUES (141, '独孤无敌');
INSERT INTO `bb`(`uid`, `name`) VALUES (151, '陈磊');
INSERT INTO `bb`(`uid`, `name`) VALUES (155, '采花大盗');
UNION 操作符用于合并两个或多个 SELECT 语句的结果集。UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。
union 是对数据进行并集操作,不包括重复行,同时进行默认排序
从效率上说,UNION ALL 要比UNION快很多,Union all 是对数据进行并集操作,包括重复行,不进行排序
select * from aa;
image.png
select * from bb;
image.png
aa表和bb表合并查询结果
select * from aa union select * from bb;
image.png
如果想使用ORDER BY或LIMIT子句来对全部UNION结果进行分类或限制,则应对单个地SELECT语句加圆括号,并把ORDER BY或LIMIT放到最后一个的后面
(select uid,name from aa) union (select uid,name from bb)ORDER BY uid desc limit 10;两个SQL都得加上()。
image.png
或者如下写SQL也可以
select uid,name from (select uid,name from aa union select uid,name from bb) t order by uid desc LIMIT 10;记得给 括号合并的表取上别名,否则报错 如下图
select uid,name from (select uid,name from aa union select uid,name from bb) order by uid desc LIMIT 10;没取别名 t 报错
image.png
如果用到分组。
select uid,group_concat(name )from (select uid,name from aa union select uid,name from bb) t group by uid order by uid desc LIMIT 10;
image.png
select uid,name from (select uid,name from aa union select uid,name from bb) t group by uid order by uid desc LIMIT 10;
image.png
运行上面那个SQL会报错,因为5.7版本之后的MYSQL不在group by里的字段 跟在select会报错解决办法是,用函数 any_value(字段名)
select any_value(name),max(uid)from (select uid,name from aa union select uid,name from bb) t group by uid order by uid desc LIMIT 10;
运行上面的SQL 不报错了
image.png
any_value(字段名)允许,非分组字段的出现