选择每个组中的最后一条记录

时间:2016-11-10 10:16:51

标签: mysql sql group-by

我有一张桌子:

id    group_id    name    linked_group
1     1           Name1
2     1           Name2
3     1           Name3
4     1           Name4
5     2           Name5
6     2           Name6   3
7     2           Name7
8     3           Name8
9     3           Name9
10    4           Name10
11    4           Name11

我需要使用linked_group检索每个组中的最后一条记录:

id    group_id    name    linked_group
4     1           Name4
9     3           Name9
11    4           Name11

怎么做? 附:我需要忽略group_id = 2,因为这个group_id需要与group_id = 3

结合

5 个答案:

答案 0 :(得分:0)

SELECT Your_tableName.id ,Your_tableName.group_id ,name,linked_group
FROM Your_tableName
    JOIN (SELECT MAX(id) id, group_id
          FROM Your_tableName
          GROUP BY group_id) A ON A.id = Your_tableName.id

答案 1 :(得分:0)

试试这个

SELECT g.id,g.group_id,g.name,g.linked_group
FROM GroupTable g LEFT JOIN GroupTable g2
 ON (g.group_id = g2.group_id AND g.id < g2.id)
WHERE g2.id IS NULL;

enter image description here

答案 2 :(得分:0)

如果表格不是太大,请使用以下查询。

select max_id, group_id, name  from table_name , (select max(id) as max_id  from table_name group by group_id) tmp where id = max_id ;

答案 3 :(得分:0)

这是使用行号模拟的另一种方法。请注意where not exists语句,以忽略具有链接组的group_ids。

select  s.id,s.group_id,s.name,s.linked_group
from
(
select  t.*,
          if(t.group_id <> @p , @rownumber:=1,@rownumber:=@rownumber + 1) rownumber,
          @p:=t.group_id
from    t t, (select @rownumber:=0,@p:=0) rn 
where not exists (select * from t t1 where t1.group_id = t.group_id and t1.linked_group is not null) 
order   by t.group_id,t.id desc
) s 
where s.rownumber = 1

答案 4 :(得分:0)

试一试。希望它能起作用:))

SELECT a.*
FROM table_name a LEFT JOIN table_name b
ON (a.group_id = b.group_id AND a.id < b.id)
WHERE a.group_id <> 2 AND b.id IS NULL;