能否用 ORDER BY 在兩張不同的表中顯示兩列不同的列?


為此,你可以使用 UNION 和 ORDER BY 子句。我們首先建立一個表 -

mysql> create table DemoTable1
(
   Amount int
);
Query OK, 0 rows affected (0.63 sec)

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

mysql> insert into DemoTable1 values(234);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1 values(567);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(134);
Query OK, 1 row affected (0.43 sec)

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

mysql> select *from DemoTable1;

這樣會輸出以下內容 -

+--------+
| Amount |
+--------+
|    234 |
|    567 |
|    134 |
+--------+
3 rows in set (0.00 sec)

以下是建立第二個表後的查詢 -

mysql> create table DemoTable2
(
   Price int
);
Query OK, 0 rows affected (0.73 sec)

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

mysql> insert into DemoTable2 values(134);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(775);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable2 values(121);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable2 values(882);
Query OK, 1 row affected (0.09 sec)

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

mysql> select *from DemoTable2;

這樣會輸出以下內容 -

+-------+
| Price |
+-------+
|   134 |
|   775 |
|   121 |
|   882 |
+-------+
4 rows in set (0.00 sec)

以下是使用 ORDER BY 在兩個不同的表中顯示兩列不同的列的查詢 -

mysql> select distinct Amount from DemoTable1
   UNION
   select distinct Price from DemoTable2
   order by Amount;

這樣會輸出以下內容 -

+--------+
| Amount |
+--------+
|    121 |
|    134 |
|    234 |
|    567 |
|    775 |
|    882 |
+--------+
6 rows in set (0.00 sec)

更新日期: 01-Oct-2019

583 次瀏覽

啟動您的事業

完成課程以獲得認證

入門
廣告
© . All rights reserved.