MYSQL使用Union將兩張表的數(shù)據(jù)合并顯示
union:用于連接兩個以上的 SELECT 語句的結(jié)果組合到一個結(jié)果集合中。多個 SELECT 語句會刪除重復的數(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 t1UNIONselect 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 t1UNION ALLselect 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 t1UNION ALLselect 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 t1UNION ALLselect 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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Oracle 11g透明數(shù)據(jù)加密安全特性解析2. MySQL為什么要避免大事務以及大事務解決的方法3. MYSQL SQL查詢近7天一個月的數(shù)據(jù)的操作方法4. 無責任Oracle圖書簡評 (1)5. 輕松掌握Oracle數(shù)據(jù)庫Where條件執(zhí)行順序6. Oracle內(nèi)部工具Block Corruption介紹7. 解讀Oracle中代替like進行模糊查詢的方法instr(更高效)8. 在SQL Server數(shù)據(jù)庫中如何減少死鎖發(fā)生9. Mybatis 動態(tài)表名+Map參數(shù)傳遞+批量操作詳解10. 保“庫”之路:Oracle數(shù)據(jù)庫性能保護
