2015-12-04 65 views
0

比方說,我有如下表:選擇從表(MS SQL Server中,SQLite的)最新版本

ID | UID | Version | Content 
---+-----+---------+----------------------------- 
1 | 1 |  1 | Something 
2 | 1 |  2 | Something (changed) 
3 | 2 |  1 | Alice has a cat 
4 | 2 |  2 | Alice has a cat and a dog 
5 | 2 |  3 | Alice has a cat and a canary 

我需要創建查詢,這將返回所有對象,但只有最新版本,所以在這種情況下:

ID | UID | Version | Content 
---+-----+---------+----------------------------- 
2 | 1 |  2 | Something (changed) 
5 | 2 |  3 | Alice has a cat and a canary 

由於SQL方言不同,我會運行MS SQL Server 2008上的這個查詢的SQLite 3

我怎樣才能做到這一點?

回答

2

NOT EXISTS查詢:

select * 
from tablename t1 
where not exists (select 1 from tablename t2 
        where t2.uid = t1.uid 
        and t2.version > t1.version) 

JOIN查詢:

select t1.* 
from tablename t1 
    join (select uid, max(version) as version from tablename group by uid) t2 
    on t2.uid = t1.uid and t2.version = t1.version 

相關子查詢:

select t1.* 
from tablename t1 
where t1.version = (select max(version) from tablename t2 
        where t2.uid = t1.uid) 

IN子查詢:

select * 
from tablename 
where (uid, version) IN (select uid, max(version) from tablename 
         group by uid) 
0

有幾種不同的方法可以解決這個問題。但是每種方法都遵循相同的原則。

查詢的一部分將標識每個UID的最新版本。這將用於過濾記錄集。

在下面的例子中,我發現每個UID的當前版本都使用了子查詢,然後我用它來過濾主記錄集。

Example

/* This table gives us some sample records 
* to experiment with. 
*/ 
DECLARE @Example TABLE 
    (
     ID   INT    PRIMARY KEY, 
     [UID]  INT    NOT NULL, 
     [Version] INT    NOT NULL, 
     Content  VARCHAR(255) NOT NULL 
    ) 
; 

/* Populate the sample data. 
*/ 
INSERT INTO @Example 
    (
     ID, 
     [UID], 
     [Version], 
     Content 
    ) 
VALUES 
    (1, 1, 1, 'Something'), 
    (2, 1, 2, 'Something (changed)'), 
    (3, 2, 1, 'Alice has a cat'), 
    (4, 2, 2, 'Alice has a cat and a dog'), 
    (5, 2, 3, 'Alice has a cat and a canary') 
; 

/* Return the most recent version of each UID. 
* This is done by using a sub query to calcualte the max of each UIDs version. 
*/ 
SELECT 
    e.* 
FROM 
    @Example AS e 
     INNER JOIN 
      ( 
       /* This sub query finds the max version of 
       * each UID. 
       */ 
       SELECT 
        [UID], 
        MAX([Version]) AS Current_Version 
       FROM 
        @Example  
       GROUP BY 
        [UID] 
      ) AS mv 
     ON mv.[UID]   = e.[UID] 
     AND mv.Current_Version = e.[Version] 
;