一個 MySQL 查詢,用於在兩張表中查詢最高和最低值呢?


要從兩張表中找到最高值和最低值,請使用 MAX() 和 MIN()。由於結果要從兩張表中顯示,因此需要使用 UNION。我們首先建立一個表 -

mysql> create table DemoTable1
(
   UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score1 int
);
Query OK, 0 rows affected (0.76 sec)

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

mysql> insert into DemoTable1(Score1) values(56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1(Score1) values(76);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1(Score1) values(65);
Query OK, 1 row affected (0.09 sec)

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

mysql> select *from DemoTable1;

這將產生以下輸出 -

+----------+--------+
| UniqueId | Score1 |
+----------+--------+
|        1 |     56 |
|        2 |     76 |
|        3 |     65 |
+----------+--------+
3 rows in set (0.00 sec)

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

mysql> create table DemoTable2
(
   UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score2 int
);
Query OK, 0 rows affected (0.93 sec)

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

mysql> insert into DemoTable2(Score2) values(67);
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable2(Score2) values(94);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable2(Score2) values(98);
Query OK, 1 row affected (0.08 sec)

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

mysql> select *from DemoTable2;

這將產生以下輸出 -

+----------+--------+
| UniqueId | Score2 |
+----------+--------+
|        1 |     67 |
|        2 |     94 |
|        3 |     98 |
+----------+--------+
3 rows in set (0.00 sec)

以下是查詢 2 個表中的最高值和最低值的查詢 -

mysql> select max(commonValue) AS Highest_Value,min(commonValue) AS Lowest_Value from
(
   select Score1 as commonValue from DemoTable1
   union
   select Score2 as commonValue from DemoTable2
) tbl;

這將產生以下輸出 -

+---------------+--------------+
| Highest_Value | Lowest_Value |
+---------------+--------------+
|            98 |           56 |
+---------------+--------------+
1 row in set (0.04 sec)

更新於: 01-10-2019

129 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告