MYSQL使用Union將兩張表的數(shù)據(jù)合并顯示
使用UNION操作符
union:用于連接兩個(gè)以上的 SELECT 語句的結(jié)果組合到一個(gè)結(jié)果集合中。多個(gè) SELECT 語句會(huì)刪除重復(fù)的數(shù)據(jù)。
使用union操作符會(huì)將多張表中相同的數(shù)據(jù)取值一次,如果想將表1和表2中的值完整的顯示出來,可以使用union all。
演示
小伙伴們自行創(chuàng)建一下表。
表1數(shù)據(jù)如下:

表2數(shù)據(jù)如下:

OK,表數(shù)據(jù)已經(jīng)創(chuàng)建完成,一共五條數(shù)據(jù),接下來我們?nèi)タ匆豢磚nion 和 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只會(huì)查出來四條數(shù)據(jù)。其中兩條是相同的數(shù)據(jù),則顯示一條。
使用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條數(shù)據(jù),ps:相同的數(shù)據(jù)也會(huì)查詢出來。
拓展:
為了區(qū)分哪張表中的數(shù)據(jù),我們可以這樣做
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

將兩張表中的數(shù)據(jù)按時(shí)間排序
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

到此這篇關(guān)于MYSQL使用Union將兩張表的數(shù)據(jù)合并顯示的文章就介紹到這了,更多相關(guān)mysql數(shù)據(jù)合并顯示內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL COUNT用法終極指南:(*)/(1)/(列名)哪個(gè)更高效
在日常開發(fā)中,幾乎每個(gè)程序員都用過COUNT()函數(shù),那么COUNT(*)、COUNT(1)、COUNT(column)有什么區(qū)別,哪個(gè)更快,下面小編就來和大家簡(jiǎn)單講講吧2025-08-08
如何解決MySQL安裝遇到Start service紅叉問題
在安裝MySQL時(shí),若遇到StartService步驟打紅叉無法繼續(xù),可通過計(jì)算機(jī)管理以管理員身份運(yùn)行服務(wù),找到MySQL服務(wù),更改為本地系統(tǒng)賬戶登錄,解決安裝問題,此方法為實(shí)際操作經(jīng)驗(yàn),可供參考,確保安裝順利完成2024-10-10
MySQL?中如何歸檔數(shù)據(jù)的實(shí)現(xiàn)方法
本文主要介紹了MySQL?中如何歸檔數(shù)據(jù)的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Navicat連接mysql報(bào)錯(cuò)2003(10060)的解決方法
本來好好的navicat連接數(shù)據(jù)庫,突然間今天就打不開數(shù)據(jù)庫了,下面這篇文章主要給大家介紹了關(guān)于Navicat連接mysql報(bào)錯(cuò)2003(10060)的解決方法,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04

