MySQL 查询以选择最大和最小工资行?
为此,请使用子查询以及 MIN() 和 MAX()。要显示最大值和最小值,请使用 UNION ALL。让我们先创建一个表 -
mysql> create table DemoTable -> ( -> EmployeeName varchar(20), -> EmployeeSalary int -> ); Query OK, 0 rows affected (0.70 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('Bob',8800); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Chris',9800); Query OK, 1 row affected (0.63 sec) mysql> insert into DemoTable values('David',7600); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Sam',9600); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+--------------+----------------+ | EmployeeName | EmployeeSalary | +--------------+----------------+ | Bob | 8800 | | Chris | 9800 | | David | 7600 | | Sam | 9600 | +--------------+----------------+ 4 rows in set (0.00 sec)
以下是要选择最小工资行的查询 -
mysql> select *from DemoTable -> where EmployeeSalary in ( select max(EmployeeSalary) from DemoTable -> union all -> select min(EmployeeSalary) from DemoTable -> );
这将产生以下输出 -
+--------------+----------------+ | EmployeeName | EmployeeSalary | +--------------+----------------+ | Chris | 9800 | | David | 7600 | +--------------+----------------+ 2 rows in set (0.05 sec)
广告