Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从表中选择最新版本(MS SQL Server、SQLite)_Sql_Sql Server_Sqlite - Fatal编程技术网

从表中选择最新版本(MS SQL Server、SQLite)

从表中选择最新版本(MS SQL Server、SQLite),sql,sql-server,sqlite,Sql,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 |

比方说,我有下表:

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上运行此查询


如何实现此目标?

不存在
查询:

select *
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.uid = t1.uid
                    and t2.version > t1.version)
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 *
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.uid = t1.uid
                    and t2.version > t1.version)
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)
select *
from tablename
where (uid, version) IN (select uid, max(version) from tablename
                         group by uid)
子查询中的

select t1.*
from tablename t1
where t1.version = (select max(version) from tablename t2
                    where t2.uid = t1.uid)
select *
from tablename
where (uid, version) IN (select uid, max(version) from tablename
                         group by uid)

有几种不同的方法来解决这个问题。但每种方法都遵循相同的原则

查询的一部分将标识每个UID的最新版本。这将用于过滤记录集

在下面的示例中,我使用一个子查询找到了每个UID的当前版本,然后用它过滤主记录集