国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

MYSQL使用Union將兩張表的數據合并顯示

瀏覽:154日期:2023-10-18 08:00:49
使用UNION操作符

union:用于連接兩個以上的 SELECT 語句的結果組合到一個結果集合中。多個 SELECT 語句會刪除重復的數據。

使用union操作符會將多張表中相同的數據取值一次,如果想將表1和表2中的值完整的顯示出來,可以使用union all。

演示

小伙伴們自行創建一下表。

表1數據如下:

MYSQL使用Union將兩張表的數據合并顯示

表2數據如下:

MYSQL使用Union將兩張表的數據合并顯示

OK,表數據已經創建完成,一共五條數據,接下來我們去看一看union 和 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

MYSQL使用Union將兩張表的數據合并顯示

我們可以看到使用union只會查出來四條數據。其中兩條是相同的數據,則顯示一條。

使用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

MYSQL使用Union將兩張表的數據合并顯示

使用union all查出5條數據,ps:相同的數據也會查詢出來。

拓展:

為了區分哪張表中的數據,我們可以這樣做

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

MYSQL使用Union將兩張表的數據合并顯示

將兩張表中的數據按時間排序

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

MYSQL使用Union將兩張表的數據合并顯示

到此這篇關于MYSQL使用Union將兩張表的數據合并顯示的文章就介紹到這了,更多相關mysql數據合并顯示內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: MySQL 數據庫
相關文章:
主站蜘蛛池模板: 盘锦市| 巫溪县| 栖霞市| 珠海市| 阿鲁科尔沁旗| 呼图壁县| 华池县| 大安市| 抚州市| 确山县| 郑州市| 阜南县| 兴业县| 平昌县| 余干县| 岳阳市| 信宜市| 普陀区| 冀州市| 黎城县| 昌图县| 中宁县| 漯河市| 梁河县| 漳浦县| 嘉定区| 长治市| 柳河县| 上栗县| 丰台区| 抚松县| 江城| 三台县| 汉源县| 山阴县| 平阳县| 龙泉市| 开远市| 巴南区| 仙桃市| 正蓝旗|