從三個列中選擇不同值並在使用 MySQL 的單一列中顯示


為此,在單個 MySQL 查詢中多次使用 UNION。讓我們先建立一個表 −

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

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

mysql> insert into DemoTable values(20,null,null);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(20,null,null);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(20,null,null);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(10,null,null);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(80,20,100);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(10,null,null);
Query OK, 1 row affected (0.16 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     20 |   NULL |   NULL |
|     20 |   NULL |   NULL |
|     20 |   NULL |   NULL |
|     10 |   NULL |   NULL |
|     80 |     20 |    100 |
|     10 |   NULL |   NULL |
+--------+--------+--------+
6 rows in set (0.00 sec)

以下查詢可從 3 個列中選擇不同值,並放入 1 個列 −

mysql> select *from
   -> (
   -> select Value1 as AllValue from DemoTable
   -> union
   -> select Value2 as AllValue from DemoTable
   -> union
   -> select Value3 as AllValue from DemoTable
   -> ) tbl where AllValue IS NOT NULL
   -> order by AllValue;

這將產生以下輸出 −

+----------+
| AllValue |
+----------+
|       10 |
|       20 |
|       80 |
|      100 |
+----------+
4 rows in set (0.00 sec)

更新日期: 2019 年 12 月 13 日

484 次瀏覽

開啟您的 事業

完成課程即可獲得認證

شروع کریں
اشتہارات
© . All rights reserved.