2015-11-12 65 views
1

这里是我的表:如何在MySQL中完全按两个字段进行分组?

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我应该写?

+0

SQL语句对我来说似乎很好。你为什么认为这是错的? – Mureinik

+0

你想得到'最新的gw_ref和最新的gw_time'或''最新的gw_ref和与之相对应的gw_time'。如果你想最新的那么你的查询似乎确定。如果你想'最新的gw_ref和它对应的gw_time',那么你在WHERE子句中包含条件来检查gw_ref =(从...中选择max(gw_ref))。 – PK20

+0

@ PK20,是的,我想与最新的'gw_name',@Mureinik,我很担心,因为我不认为我可以在字符串('gw_ref')字段使用MAX()。 – Phoenix

回答

1

如果max(gw_ref)不是根据gw_created_time组中的最新消息?

通常你应该使用ROW_NUMBER()每组下令各组内的记录,然后选择与ROW_NUMBER = 1记录。在MySQL中没有ROW_NUMBER()聚合函数,但你可以使用User-Defined variables在MySQL效仿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

+0

在这种情况下'tbl'在哪里? – Phoenix

+0

@Phoenix:我已经在tbl的答案中更改了表名。 – valex

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

相关问题