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)
阅读更多:MySQL 教程
极客教程