MySQL 行连接可以从重复的 ID 中获取最大对应值?
为此,您可以使用 GROUP BY 从句。要查找最大值,请使用 MAX() 函数。让我们首先创建一个表 -
mysql> create table DemoTable1804 ( Id int, Marks1 int, Marks2 int, Marks3 int ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令插入一些记录到表中 -
mysql> insert into DemoTable1804 values(1,56,89,34); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1804 values(1,98,null,94); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1804 values(2,34,45,78); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1804 values(2,null,67,null); Query OK, 1 row affected (0.00 sec)
使用 select 语句从表中显示所有记录 -
mysql> select * from DemoTable1804;
这将产生以下输出 -
+------+--------+--------+--------+ | Id | Marks1 | Marks2 | Marks3 | +------+--------+--------+--------+ | 1 | 56 | 89 | 34 | | 1 | 98 | NULL | 94 | | 2 | 34 | 45 | 78 | | 2 | NULL| 67 | NULL | +------+--------+--------+--------+ 4 rows in set (0.00 sec)
以下是行连接和查找最大值的查询 -
mysql> select Id,max(Marks1),max(Marks2),max(Marks3) from DemoTable1804 group by Id;
这将产生以下输出 -
+------+-------------+-------------+-------------+ | Id | max(Marks1) | max(Marks2) | max(Marks3) | +------+-------------+-------------+-------------+ | 1 | 98 | 89 | 94 | | 2 | 34 | 67 | 78 | +------+-------------+-------------+-------------+ 2 rows in set (0.00 sec)
广告