2014-01-18 143 views
0

我有兩個表具有以下數據:選擇SQL內部連接和省略某些記錄

表A

ID  DESC 
1  One 
2  Two 
3  Three 

ID是主鍵

表B顯示了我在做對ID的動作表阿

NO  ACTION  ID  DATETIME 
1  ADD   1  2012-01-01 00:00:00 
2  ADD   2  2012-01-01 00:00:00 
3  ADD   3  2012-01-01 00:00:00 
4  DELETE  2  2012-01-01 01:00:00 
5  EDIT   1  2012-01-01 02:00:00 
6  EDIT   3  2012-01-01 03:00:00 
7  DELETE  1  2012-01-01 03:00:00 
8  REVIVE  2  2012-01-01 04:00:00 
9  EDIT   2  2012-01-01 05:00:00 

NO是主鍵

這裏是總結:

ID 1:添加於2012-01-01 00:00:00,編輯於2012-01-01 02:00:00,刪除於2012-01-01 03: 00:00

ID 2:2012-01-01 00:00:00 ADD,2012-01-01 01:00:00 DELETE,2012-01-01 04:00:00 REVIVE,編輯2012-01-01 05:00:00

ID 3:2012-01-01 00:00:00,編輯ADD 2012-01-01 03:00:00

我如何查詢表得到如下結果:

表C

NO  DESC 
2  Two 
3  Three 

我想要做的是:查詢表A中沒有在最後交易時間刪除操作,所以我只得到有效ID

我試圖做內部聯接,但如何在最後一次交易時忽略具有刪除操作的ID。任何建議/意見將不勝感激。

+0

是'NO'主鍵?它是否符合'DATETIME'? –

+0

@KubaWyrostek表主鍵是ID列,表B主鍵是NO列(用於事務索引)。這意味着表B將始終處於DATETIME順序。順便說一句我正在使用postgres – wrez

回答

1

你可以試試這個

select ID, DESC 
from A join (
select id, action, rank() over (partition by id order by datetime desc) ranking 
from B 
) B on (B.ranking = 1 and B.id = A.id and B.action <> 'DELETE') 
0

假設比NO是的TableB主鍵,下令根據DATETIME

select 
    TableA.ID, TableA.DESC 
from TableA inner join 
    (select ID, max(NO) as MaxNO from TableB group by ID) as MaxNOs 
    on TableA.ID = MaxNOs.ID 
     inner join TableB on MaxNOs.ID = TableB.ID and MaxNOs.MaxNO = TableB.NO 
where 
    TableB.ACTION <> 'DELETE'