简体   繁体   中英

Select last record in each group

I have a table:

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

I need to retrieve last record in each group with linked_group:

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

How to do this? PS I need to ignore group_id = 2, because this group_id need union with group_id = 3

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

Try this

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;

在此输入图像描述

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

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 ;

Here's another approach using row number simulation. Note the where not exists statement to ignore group_ids with a linked group.

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

Give it a try. Hope it will work :)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM