mysql数据合并显示 MYSQL使用Union将两张表的数据合并显示

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mysql数据合并显示 MYSQL使用Union将两张表的数据合并显示

周董思密达   2021-08-04 我要评论
想了解MYSQL使用Union将两张表的数据合并显示的相关内容吗,周董思密达在本文为您仔细讲解mysql数据合并显示的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:mysql数据合并显示,mysql,UNION操作符,下面大家一起来学习吧。

使用UNION操作符

union:用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。

使用union操作符会将多张表中相同的数据取值一次,如果想将表1和表2中的值完整的显示出来,可以使用union all。

演示

小伙伴们自行创建一下表。

表1数据如下: 

表2数据如下:

OK,表数据已经创建完成,一共五条数据,接下来我们去看一看union 和 union all 的使用。

使用union 看一下效果:

select t1.id id, t1.name name, t1.description description,t1.create_time time from table1 t1
UNION
select t2.id id, t2.name name, t2.description description,t2.create_date time from table2 t2

我们可以看到使用union只会查出来四条数据。其中两条是相同的数据,则显示一条。

使用union all 看一下效果:

select t1.id id, t1.name name, t1.description description,t1.create_time time from table1 t1
UNION ALL
select t2.id id, t2.name name, t2.description description,t2.create_date time from table2 t2

使用union all查出5条数据,ps:相同的数据也会查询出来。

拓展: 

为了区分哪张表中的数据,我们可以这样做

select t1.id id, t1.name name, t1.description description,t1.create_time time,'table1' type from table1 t1
UNION ALL
select t2.id id, t2.name name, t2.description description,t2.create_date time,'table2' type  from table2 t2

将两张表中的数据按时间排序

select t3.* from (select t1.id id, t1.name name, t1.description description,t1.create_time time,'table1' type from table1 t1
UNION ALL
select t2.id id, t2.name name, t2.description description,t2.create_date time,'table2' type  from table2 t2) t3 order by t3.time desc

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们