要了解多列上的GROUP BY和MAX,让我们首先创建一个表。创建表的查询如下-
mysql> create table GroupByMaxDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> CategoryId int, -> Value1 int, -> Value2 int -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(10,100,50); mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(10,100,70); mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(10,50,100); mysql> insert into GroupByMaxDemo(CategoryId, Value1,Value2) values(20,180,150);
使用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)
以下是在多列上使用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)