服务器之家

服务器之家 > 正文

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

时间:2021-09-14 17:26     来源/作者:周董思密达

使用union操作符

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

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

演示

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

表1数据如下: 

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

表2数据如下:

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

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

使用union 看一下效果:

?
1
2
3
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

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

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

使用union all 看一下效果:

?
1
2
3
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

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

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

拓展: 

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

?
1
2
3
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

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

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

?
1
2
3
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

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

到此这篇关于mysql使用union将两张表的数据合并显示的文章就介绍到这了,更多相关mysql数据合并显示内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/zz0828zz/article/details/118576156

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部