iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >MYSQL使用Union将两张表的数据合并显示
  • 1032
分享到

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

mysql数据合并显示mysqlUNION操作符 2022-05-23 16:05:47 1032人浏览 安东尼
摘要

使用UNION操作符 union:用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。 使用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

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

您可能感兴趣的文档:

--结束END--

本文标题: MYSQL使用Union将两张表的数据合并显示

本文链接: https://www.lsjlt.com/news/10457.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作