MySQL 查询从重复列值中获取最大对应值

mysqlmysqli database更新于 2025/12/25 6:04:17

首先我们创建一个表 −

mysql> create table DemoTable(
   ProductName varchar(100),
   ProductPrice int
);
Query OK, 0 rows affected (0.68 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('Product-1',56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-2',78);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('Product-1',88);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-2',86);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Product-1',45);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Product-3',90);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Product-2',102);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Product-3',59);
Query OK, 1 row affected (0.13 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------------+--------------+
| ProductName | ProductPrice |
+-------------+--------------+
| Product-1   | 56           |
| Product-2   | 78           |
| Product-1   | 88           |
| Product-2   | 86           |
| Product-1   | 45           |
| Product-3   | 90           |
| Product-2   | 102          |
| Product-3   | 59           |
+-------------+--------------+
8 rows in set (0.00 sec)

以下是从重复列值中获取最大对应值的查询。在这里,我们查找重复列(如 Product-1、Product-2 等)的最大 ProductPrice −

mysql> select ProductName,MAX(ProductPrice) from DemoTable group by ProductName;

这将产生以下输出 −

+-------------+-------------------+
| ProductName | MAX(ProductPrice) |
+-------------+-------------------+
| Product-1   | 88                |
| Product-2   | 102               |
| Product-3   | 90                |
+-------------+-------------------+
3 rows in set (0.00 sec)

相关文章


有用资源