在 MySQL 中对多列使用 GROUP BY 和 MAX?


为了理解针对多列的 GROUP BY 和 MAX,我们先创建一个表。创建表的查询如下 −

mysql> create table GroupByMaxDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> CategoryId int,
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.68 sec)

示例

使用 insert 命令插入一些记录到表中。查询如下 −

mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(10,100,50);
Query OK, 1 row affected (0.15 sec)
mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(10,100,70);
Query OK, 1 row affected (0.21 sec)
mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(10,50,100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(20,180,150);
Query OK, 1 row affected (0.19 sec)

使用 select 语句从表中显示所有记录。查询如下 −

mysql> select *from GroupByMaxDemo;

输出

+----+------------+--------+--------+
| Id | CategoryId | Value1 | Value2 |
+----+------------+--------+--------+
|  1 |         10 |    100 |     50 |
|  2 |         10 |    100 |     70 |
|  3 |         10 |     50 |    100 |
|  4 |         20 |    180 |    150 |
+----+------------+--------+--------+
4 rows in set (0.00 sec)

Learn MySQL in-depth with real-world projects through our MySQL certification course. Enroll and become a certified expert to boost your career.

示例

以下是对多列使用 GROUP BY 和 MAX 的查询 −

mysql> select tbl2.CategoryId, tbl2.Value1, max(tbl2.Value2)
   -> from
   -> (
   -> select CategoryId, max(Value1) as `Value1`
   -> from GroupByMaxDemo
   -> group by CategoryId
   -> ) tbl1
   -> inner join GroupByMaxDemo tbl2 on tbl2.CategoryId = tbl1.CategoryId and tbl2.Value1 = tbl1.Value1
   -> group by tbl2.CategoryId, tbl2.Value1;

输出

+------------+--------+------------------+
| CategoryId | Value1 | max(tbl2.Value2) |
+------------+--------+------------------+
|         10 |    100 |               70 |
|         20 |    180 |              150 |
+------------+--------+------------------+
2 rows in set (0.00 sec)

更新时间: 26-6 月 2020 年

2K+ 浏览量

开启你的 职业生涯

完成课程即可获得认证

开始
广告