使用 MySQL 將列合併到行中?


要將列合併到行中,請使用 UNION ALL。以下是語法 −

語法

select yourColumnName1 from yourTableName
   union all
select yourColumnName2 from yourTableName;

首先讓我們建立一個表 −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.88 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values(100,200);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(500,600);
Query OK, 1 row affected (0.18 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

將生成以下輸出 −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|    100 |    200 |
|    500 |    600 |
+--------+--------+
2 rows in set (0.00 sec)

這是將列合併到行中的查詢 −

mysql> select Value1 from DemoTable
   -> union all
   -> select Value2 from DemoTable;

將生成以下輸出 −

+--------+
| Value1 |
+--------+
|    100 |
|    500 |
|    200 |
|    600 |
+--------+
4 rows in set (0.00 sec)

更新於:2019-12-12

2K+ 次瀏覽

開啟您的 職業生涯

完成課程認證

開始學習
廣告