如何在MySQL中将两个字段分组?

时间:2015-11-12 07:58:18

标签: mysql sql

这是我的表:

gw_id |gw_payload |gw_name |gw_ref |gw_time             |gw_created_time     |
------|-----------|--------|-------|--------------------|--------------------|
1     |aaa        |PHP     |0.1.1  |2015-11-11 11:34:41 |2015-11-11 13:59:44 |
2     |bbb        |PHP     |0.1.1  |2015-11-11 11:34:41 |2015-11-11 13:59:57 |
3     |ccc        |RUBY    |0.1.2  |2015-11-10 01:34:41 |2015-11-10 13:59:57 |
4     |ddd        |RUBY    |0.1.4  |2015-11-10 02:34:41 |2015-11-10 16:59:57 |

我想按gw_name抓取记录组,我希望得到最新的gw_ref和最新的gw_time。所以我想在下面:

gw_name |gw_ref_max |gw_time_max         |
--------|-----------|--------------------|
RUBY    |0.1.4      |2015-11-10 02:34:41 |
PHP     |0.1.1      |2015-11-11 11:34:41 |

我正在使用这个SQL,它有效,但我不认为这是正确的,我很担心:

select gw_name, max(gw_ref) as gw_ref_max, max(gw_time) as gw_time_max      
from tbl group by gw_name order by gw_time,gw_created_time desc

那么我应该编写什么样的SQL?

2 个答案:

答案 0 :(得分:1)

如果根据max(gw_ref) gw_created_time不是组中的最新内容,该怎么办?

通常,您应该每个组使用ROW_NUMBER()来对每个组内的记录进行排序,然后选择ROW_NUMBER = 1的记录。在MySQL中没有ROW_NUMBER()聚合函数,但您可以在MySQL中使用User-Defined variables来模拟ROW_NUMBER()

select *
from (
   select gw_id,gw_ref,gw_time,gw_created_time,
          @num := if(@grp = gw_name, @num + 1, 1) as row_number,
          @grp := gw_name as dummy
  from tbl,(select @num := 0, @grp := null) as T
  order by gw_created_time DESC
) as x where x.row_number = 1;

SQLFiddle demo

另见: How to select the first/least/max row per group in SQL

答案 1 :(得分:1)

如果您需要获取与其对应的最新gw_refgw_time,则可以使用子查询。

select * from (
    select gw_name, gw_ref, gw_time
    from tbl
    order by gw_ref desc, gw_time desc, gw_created_time desc
) as s
group by s.gw_name

请注意按gw_ref排序,其值可能为 0.1.10 (大于 0.1.2 )。您可以尝试SUBSTRING_INDEX订购。