如何在單個 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP