MYSQL使用Union將兩張表的數(shù)據(jù)合并顯示
使用UNION操作符
union:用于連接兩個以上的 SELECT 語句的結(jié)果組合到一個結(jié)果集合中。多個 SELECT 語句會刪除重復(fù)的數(shù)據(jù)。
使用union操作符會將多張表中相同的數(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只會查出來四條數(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ù)也會查詢出來。
拓展:
為了區(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ù)按時間排序
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL安裝第四步報錯(initializing?database報錯)的圖文解決方法
這篇文章主要給大家介紹了關(guān)于MySQL安裝第四步報錯(initializing?database報錯)的解決方法,"initializing?database"?通常出現(xiàn)在安裝MySQL的過程中,表示MySQL數(shù)據(jù)庫初始化過程中遇到了問題,需要的朋友可以參考下2024-06-06MySQL數(shù)據(jù)庫導(dǎo)出與導(dǎo)入及常見錯誤解決
MySQL數(shù)據(jù)庫導(dǎo)出與導(dǎo)入的過程中將會發(fā)生眾多不可預(yù)知的錯誤,本文整理了一些常見錯誤及相應(yīng)的解決方法,遇到類似情況的朋友可以參考下,希望對大家有所幫助2013-07-07MySQL中無GROUP BY情況下直接使用HAVING語句的問題探究
這篇文章主要介紹了MySQL中無GROUP BY情況下直接使用HAVING語句的問題探究,同時探究了該情況下MAX與MIN功能的使用情況,需要的朋友可以參考下2015-05-05MySQL中使用load data命令實現(xiàn)數(shù)據(jù)導(dǎo)入的方法
MySQL支持load data命令的數(shù)據(jù)導(dǎo)入,該方式比直接的insert的效率要高,按照官方的說法是要比insert語句快上20倍2013-10-10