源码家族
当前位置:首页 > 资讯中心

资讯中心

【 group by 与max 一起用可以吗? 】

发布时间:2022-02-10 13:54:26 阅读次数:336

  1. mysql> select * from test;  

  2. +----+-------+------+-------+  

  3. | id | name  | age  | class |  

  4. +----+-------+------+-------+  

  5. |  1 | qiu   |   22 |     1 |   

  6. |  2 | liu   |   42 |     1 |   

  7. |  4 | zheng |   20 |     2 |   

  8. |  3 | qian  |   20 |     2 |   

  9. |  0 | wang  |   11 |     3 |   

  10. |  6 | li    |   33 |     3 |   

  11. +----+-------+------+-------+  

  12. rows in set (0.00 sec)  


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

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


[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片

  1. mysql> select id,name,max(age),class from test group by class;  

  2. +----+-------+----------+-------+  

  3. | id | name  | max(age) | class |  

  4. +----+-------+----------+-------+  

  5. |  1 | qiu   |       42 |     1 |   

  6. |  4 | zheng |       20 |     2 |   

  7. |  0 | wang  |       33 |     3 |   

  8. +----+-------+----------+-------+  

  9. rows in set (0.00 sec)  

虽然找到的age是最大的age,但是与之匹配的用户信息却不是真实的信息,而是group by分组后的第一条记录的基本信息。


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


[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片

  1. mysql> select * from (  

  2.     -> select * from test order by age descas b  

  3.     -> group by class;  

  4. +----+-------+------+-------+  

  5. | id | name  | age  | class |  

  6. +----+-------+------+-------+  

  7. |  2 | liu   |   42 |     1 |   

  8. |  4 | zheng |   20 |     2 |   

  9. |  6 | li    |   33 |     3 |   

  10. +----+-------+------+-------+  

  11. rows in set (0.00 sec)  


方法2:

    

  1. select * from test t where t.age = (select max(age) from test where t.class = class) order by class; 

在laravel中的使用

$maxList=DB::table('data')->select('id','report_at','column_value','day')
   ->whereBetween('report_at',[$param['start_time'],$param['end_time'].' 23:59:59'])
   ->where(['column_name'=>$columnName,'monitor_id'=>$monitor_id])->orderBy('column_value','desc');

 

$result = DB::(data')->select('report_data.id','report_data.report_at','report_data.column_value','report_data.day')
   ->joinSub($maxList,'maxList', function($join) {
       $join->on('report_data.id', '=', 'maxList.id');
   })
   ->groupBy('report_data.day')->get()->toArray();



上一篇:当PHP遇见 Serverless