2016-11-10 96 views
1

在最後一個記錄我有一個表:選擇每個組

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 

如何做到這一點? P.S.我需要忽略GROUP_ID = 2,因爲這需要GROUP_ID工會與GROUP_ID = 3

+0

爲什麼group_id 2沒有出現在你的結果集中? –

+0

linked_group = 3,需要與group_id = 2聯合 –

+0

如果有任何group_id成員有鏈接組忽略該組? –

回答

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 
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

+0

需要忽略group_id = 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 ; 
+0

會引發錯誤。你需要一個相關的子查詢,就像在Mansoor的答案中一樣。 – jarlh

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:[email protected] + 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 
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;