MYsql max求对应对大值的字段

MySQL中MAX函数与Group By一起使用的注意事项

mysql> select * from test;
+----+-------+------+-------+
| id | name  | age  | class |
+----+-------+------+-------+
|  1 | qiu   |   22 |     1 | 
|  2 | liu   |   42 |     1 | 
|  4 | zheng |   20 |     2 | 
|  3 | qian  |   20 |     2 | 
|  0 | wang  |   11 |     3 | 
|  6 | li    |   33 |     3 | 
+----+-------+------+-------+
6 rows in set (0.00 sec)

如果想找到每个class里面的最大的age,则需要使用group by和max。

如下的sql语句,则输出结果有错误:

mysql> select id,name,max(age),class from test group by class;
+----+-------+----------+-------+
| id | name  | max(age) | class |
+----+-------+----------+-------+
|  1 | qiu   |       42 |     1 | 
|  4 | zheng |       20 |     2 | 
|  0 | wang  |       33 |     3 | 
+----+-------+----------+-------+
3 rows in set (0.00 sec)
虽然找到的age是最大的age,但是与之匹配的用户信息却不是真实的信息,而是group by分组后的第一条记录的基本信息。

如果我使用以下的语句进行查找,则可以返回真实的结果。

mysql> select * from (
  -> select * from test order by age desc) as b
  -> group by class;
+----+-------+------+-------+
| id | name  | age  | class |
+----+-------+------+-------+
|  2 | liu   |   42 |	 1 | 
|  4 | zheng |   20 |	 2 | 
|  6 | li	|   33 |	 3 | 
+----+-------+------+-------+
3 rows in set (0.00 s

查询一个表中类别字段中Max()最大值对应的记录

     select max(level) as level,role_name,account_id from( select * from role_data where account_id in ($str) order by level desc) as c; mysql>  select db_server,max(db_id) from (select * from rg_db_address where db_port in(6666,5555) order by db_id desc) as c group by db_id; select db_server,db_id from  rg_db_address as a where db_id =(select max(b.db_id) from rg_db_address as b where a.db_id = b.db_id and b.db_port in (4444,5555,6666)); select id,kind,click_num from code as a    where  click_num=(select max(b.click_num)                     from code as b                     where a.kind = b.kind  and b.kind                   ); 
没有更多评论了^^
评论加载失败, 重新加载
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值