如何在單個 MySQL 查詢中查詢最小值和最大值?


若要使用單個查詢查詢最小值和最大值,可使用 MySQL UNION。我們首先建立一個表 −

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

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

mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(120);
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from DemoTable;

這將生成以下輸出 −

+-------+
| Price |
+-------+
| 88    |
| 100   |
| 98    |
| 120   |
+-------+
4 rows in set (0.00 sec)

以下是在一個 MySQL 查詢中查詢最小值和最大值的查詢 −

mysql> select Price from DemoTable where Price=(select min(Price) from DemoTable)
   UNION
   select Price from DemoTable where Price=(select max(Price) from DemoTable);

這將生成以下輸出 −

+-------+
| Price |
+-------+
| 88    |
| 120   |
+-------+
2 rows in set (0.00 sec)

更新於: 2019 年 9 月 27 日

342 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.